r/learnjavascript • • May 14 '21

Remove Duplicate Value from array

Post image
234 Upvotes

89 comments sorted by

View all comments

20

u/slowthedataleak May 14 '21

Does this perform better than filter()?

2

u/47milliondollars May 14 '21

Would filter even work? Or do you have to use reduce to check if the value exists yet in an accumulator?

7

u/space_scarab May 14 '21
arr.filter((el, index) => {
    return arr.indexOf(el) === index;
});

1

u/Parkreiner May 15 '21

One comment and a question.

First, this approach will not work for non-primitive values. If you're dealing with an array of arrays or an array of objects or even an array of functions, it'll just compare their references. So if the array has two objects that have the same contents but were declared separately, you'll still get values that look like duplicates. That might be just fine for some applications, but if it's not, you'll have to do a deeper comparison.

Second, is this actually better? This isn't just rhetorical; I'm actually asking. Filtering is O(n), but so is indexOf, so since the indexOf call is inside the filter, the whole operation is O(n2). Meanwhile, generating a set is also O(n), as is destructing it into an array. But since they're done back-to-back and not inside each other, it's O(2n). I know that the highest factor doesn't always tell the whole story, but are there times when the set approach would perform better?