Algorithms and Data Structures · Senior · Question 75 of 75

Why is Array.prototype.indexOf inside filter a common hidden O(n²) in code reviews?

const unique = items.filter((x, i) => items.indexOf(x) === i);

Explanation

Each of the n callbacks does a linear search, so 10,000 items mean up to 100 million comparisons. [...new Set(items)] does the same job in O(n). Spotting such nested scans is a typical senior review skill.

Further reading

Problem with a question

Algorithms and Data Structures · Senior · question 75

Test yourself

Take the Algorithms and Data Structures · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz