0

I have gone through the following JavaScript code:

 let num = [1,2,2,2,3,4,5];
 console.log([... new Set(nums)]); //which prints [1,2,3,4,5]

I did not understand what this ... device (three dots) does in this example.

halfer
  • 18,701
  • 13
  • 79
  • 158
Abdul Rahman
  • 1,399
  • 2
  • 17
  • 35

1 Answers1

1

I think you need to read Iteration first;

let nums = [1,2,2,2,3,4,5];
let setFromArray = new Set(nums);
let arrayFromSet_spread = [...setFromArray];
console.log("spread", arrayFromSet_spread);
 
// here the spread will iterate over iteratable and return current value

//arrayFromSet can be written without spread like this
let arrayFromSet_forOf = [];
for ( let el of setFromArray ) {
  arrayFromSet_forOf.push(el)
}
console.log("forOf",arrayFromSet_forOf);


// and the most naive way to iterate :)
let arrayFromSet_ManualIteration = [];
let setFromArrayIterator = setFromArray[Symbol.iterator]();
const firstElement = setFromArrayIterator.next();
const secondElement = setFromArrayIterator.next();
const thirdElement = setFromArrayIterator.next();
const fourthElement = setFromArrayIterator.next();
const fifthElement = setFromArrayIterator.next();
const sixthElement = setFromArrayIterator.next();

arrayFromSet_ManualIteration.push(firstElement);
arrayFromSet_ManualIteration.push(secondElement);
arrayFromSet_ManualIteration.push(thirdElement);
arrayFromSet_ManualIteration.push(fourthElement);
arrayFromSet_ManualIteration.push(fifthElement);
arrayFromSet_ManualIteration.push(sixthElement);

//you could just push values not the itaration object itself
//arrayFromSet_ManualIteration.push(firstElement.value);
//arrayFromSet_ManualIteration.push(secondElement.value);
//arrayFromSet_ManualIteration.push(thirdElement.value);
//arrayFromSet_ManualIteration.push(fourthElement.value);
//arrayFromSet_ManualIteration.push(fifthElement.value);

console.log('ManualIteration full objects',arrayFromSet_ManualIteration);
Mhmdrz_A
  • 3,576
  • 3
  • 11
  • 28