JavaScript Snippet

Array Equality and Duplicate Detection

Difficulty: Medium

Three related questions on arrays: are these two arrays equal in content, does this array have any duplicates at all, and how do I dedupe a list of objects by some key. Each one has a clean linear-time answer once you know which JS collection to lean on (`Set` for primitives, `Map` for keyed objects). The naive `O(n^2)` versions are fine for tiny arrays but show up in code reviews on anything bigger.

Code Snippets
/

Array Equality and Duplicate Detection

Array Equality and Duplicate Detection

Three related questions on arrays: are these two arrays equal in content, does this array have any duplicates at all, and how do I dedupe a list of objects by some key. Each one has a clean linear-time answer once you know which JS collection to lean on (`Set` for primitives, `Map` for keyed objects). The naive `O(n^2)` versions are fine for tiny arrays but show up in code reviews on anything bigger.

JavaScript
Medium
3 snippets
arrays
hash-map
set

317 views

5

The shallow ordered check is length then every with strict equality. Strict equality (===) gets you NaN !== NaN, which is rarely what you want; swap to Object.is(v, b[i]) if NaN equality matters in your data. For unordered comparison, sort copies of both inputs first (do not sort the originals) and compare position-by-position. The big watch-out is object elements: [{id:1}] vs another [{id:1}] is unequal because the inner objects are different references. For structural object equality at the leaf level, swap to JSON.stringify comparison or js-object-deep-equal.