Removing the duplicates in an array using filter()

Removing the duplicates in an array using filter()
0

#1

Can anyone explain how to remove the duplicate elements in an array.
I cant understand it.
example array = [1,3,2,5,2,1,4,2,1]


#2

Which challenge is this?


#3
const array = [1,3,2,5,2,1,4,2,1]
const newArray = array.filter((elem, i, arr) => {
  if (arr.indexOf(elem) === i) {
    return elem
  }
})

console.log(newArray);

EDIT:
Explanation: .filter() takes three parameters - current element, index of that element and the input array. We are checking if current element elem is the first occurrence of that element in the given array. If it is - we return elem and it’s getting added to the newArray.

So when .filter() gets to the second 2 the result of arr.indexOf(elem) is 2, but current index i is 4 and this element gets skipped.


#4

Sorted Union in Intermediate Algorithm Scripting


#5

Thank you so much. Totally understood it :slight_smile:


#6

Your just give an answer
EDIT:
I didn’t see he ask with filter :slight_smile:


#7
uniqueArray = a.filter(function(item, pos) {
    return a.indexOf(item) == pos;
})