DEV Community

Discussion on: How to remove duplicates from JavaScript array

Collapse
 
chrismilson profile image
Chris Milson

You could sort the array first and then all duplicates will be next to each other:

const numbers = [1, 2, 3, 1, 2, 3, 1, 2, 3];

const unique = [...numbers].sort().filter((v, i, arr) => i === 0 || arr[i - 1] !== v)

console.log(unique) // [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ibnsamy96 profile image
Mahmoud Ibn Samy

why did you use an instance of the numbers array, not the number array itself? " [...numbers].sort() not numbers.sort() "

Collapse
 
hi_iam_chris profile image
Kristijan Pajtasev

That is a good question, sort is a destructive function. This means running sort on numbers array will change original numbers array.

Thread Thread
 
ibnsamy96 profile image
Mahmoud Ibn Samy

wow I forgot that