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);- 1
indexOfsorts the array before searching - ✓Correct answer:
indexOfscans the array for each element offilter - 3
filtercopies the whole array for each element
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.