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]
Which challenge is this?
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.
2 Likes
Sorted Union in Intermediate Algorithm Scripting
Thank you so much. Totally understood it
Your just give an answer
EDIT:
I didn’t see he ask with filter
uniqueArray = a.filter(function(item, pos) {
return a.indexOf(item) == pos;
})