Hey you programmer, okay? Let’s learn something new!
The array can often be dirty, with duplicate elements or even data that we won’t use
Then, we need to remove duplicate elements, transform the array data and then make use of it
let array = [1,2,3,4,4,5,6,7,8,6,5,4,3,2,1]; let newArray = [...new Set(array)]; console.log(newArray); // [1, 2, 3, 4, 5, 6, 7, 8]
Let’s now see in detail what happened in these lines of code
We programmed a Set object, which can only contain unique elements in it.
Combining the spread syntax, this allows iterating over the values of the original array
Finally, we create an array with the square brackets
And this way we can only have single elements in the array, solving our problem
This is the most elegant and fastest way to achieve this result.
We use advanced features of the language, and we can do with any type of data without worries
We use the Set object together with the spread to reach this result