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

// Same length AND same items in the same order.
const arraysEqual = (a, b) => {
    if (a.length !== b.length) return false;
    return a.every((v, i) => v === b[i]);
};

console.log(arraysEqual([1, 2, 3], [1, 2, 3])); // true
console.log(arraysEqual([1, 2, 3], [3, 2, 1])); // false (order matters)
console.log(arraysEqual([1, 2], [1, 2, 3]));    // false (length differs)

// 'Equal regardless of order': sort copies first, then compare.
const arraysEqualUnordered = (a, b) => {
    if (a.length !== b.length) return false;
    const sa = [...a].sort();
    const sb = [...b].sort();
    return sa.every((v, i) => v === sb[i]);
};

console.log(arraysEqualUnordered([1, 2, 3], [3, 2, 1])); // true
console.log(arraysEqualUnordered([1, 2, 2], [2, 1, 2])); // true (multiset equal)

// Caveat: object elements compare by REFERENCE, not by content.
console.log(arraysEqual([{ id: 1 }], [{ id: 1 }])); // false

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.