Skip to content
jshacks.dev
Fundamentals

How to Compare Two Arrays for Equality in JavaScript

Compare arrays by length and items with every, since === compares identity. See NaN, nested arrays, any-order checks and why JSON.stringify fails.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm, Vite and TypeScript logos.

Two arrays with the same items are not equal in JavaScript, and [1, 2, 3] === [1, 2, 3] is false. The reason is that arrays are objects, and objects compare by identity: the expression creates two separate arrays, so there are two things to compare, and the operator asks whether they are the same one. To compare contents, you write the loop yourself or call a function that does, and then decide what "equal" means for your case: the same items in the same order, the same items in any order, the same items including nested arrays and objects, or the same items by Object.is semantics for NaN. This post shows each version with its output, the popular shortcuts that give wrong answers, how to handle nested data and different orders, and the mistakes that pass review. The examples run on Node.js 24.

Why === does not work

JavaScript
const a = [1, 2, 3];
const b = [1, 2, 3];
const alias = a;

console.log(a === b, a == b, a === alias);
console.log(Object.is(a, b), Object.is(a, alias));
Text
false false true
false true

a and b hold the same values and are different objects, so every identity-based comparison, ===, == and Object.is(), says they differ. Only an alias of the same array is equal to itself. This is correct behavior for objects in general, and it is the reason a content comparison is a separate operation.

The basic version: length and every

JavaScript
const sameArray = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);

console.log(sameArray([1, 2, 3], [1, 2, 3]));
console.log(sameArray([1, 2, 3], [1, 2, 4]));
console.log(sameArray([1, 2], [1, 2, 3]));
console.log(sameArray([], []));
console.log(sameArray(["1", 2], [1, 2]));
console.log(sameArray([NaN], [NaN]));
Text
true
false
false
true
false
false

The function first compares lengths, which settles different-sized arrays in constant time, and then checks every position with ===. The string "1" and the number 1 are different, which is usually what you want. The last line is a surprise: NaN is not equal to itself under ===, so sameArray([NaN], [NaN]) is false.

NaN is not equal to itself under ===, so an array that holds NaN is never equal to another under this function, even to a copy of itself. If you want NaN to match NaN, compare with Object.is.

JavaScript
const sameWithNaN = (a, b) => a.length === b.length && a.every((value, index) => Object.is(value, b[index]));

console.log(sameWithNaN([NaN, 1], [NaN, 1]), sameWithNaN([0], [-0]), sameArray([0], [-0]));
Text
true false true

Object.is treats NaN as equal to NaN, and also distinguishes 0 from -0, which === does not. Choose the rule your data needs: === for ordinary values, Object.is when NaN can appear and you want it to match.

Why JSON.stringify is the wrong shortcut

JavaScript
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);

console.log(same([1, 2], [1, 2]));
console.log(same([undefined], [null]));
console.log(same([NaN], [null]));
console.log(same([() => {}], [null]));
console.log(same([new Date(0)], ["1970-01-01T00:00:00.000Z"]));
console.log(same([1, [2]], [1, [2]]), same([{ a: 1, b: 2 }], [{ b: 2, a: 1 }]));
Text
true
true
true
true
true
true false

The comparison works for plain data and fails for anything JSON cannot represent: undefined, NaN and functions all become null, so arrays that differ compare equal. A date becomes a string, so it matches a string. Objects whose keys were added in a different order produce different text, so equal objects compare unequal, as the last result shows. It also throws for circular structures and BigInt values, and builds two strings just to compare them. We do not use it for equality.

Other shortcuts that fail

JavaScript
console.log([1, 2].join() === ["1,2"].join());
console.log([1, [2, 3]].toString() === [1, 2, 3].toString());
console.log(String([1, 2]) === String(["1", "2"]));
console.log([1] == 1, [1, 2] == "1,2", [] == false);
Text
true
true
true
true true true

Converting arrays to strings loses the structure: one item containing a comma looks like two items, nesting disappears and numbers match strings. The loose equality operator does the same conversion behind your back, so [1] == 1 and [1, 2] == "1,2" are true. Avoid joining and toString() for equality too.

Nested arrays

The basic version compares nested arrays by identity, so it needs recursion.

JavaScript
function deepEqualArrays(a, b) {
  if (!Array.isArray(a) || !Array.isArray(b)) return Object.is(a, b);
  return a.length === b.length && a.every((value, index) => deepEqualArrays(value, b[index]));
}

console.log(sameArray([1, [2, 3]], [1, [2, 3]]));
console.log(deepEqualArrays([1, [2, 3]], [1, [2, 3]]));
console.log(deepEqualArrays([1, [2, [3]]], [1, [2, [4]]]));
console.log(deepEqualArrays([NaN, [1]], [NaN, [1]]));
console.log(deepEqualArrays([{ a: 1 }], [{ a: 1 }]));
Text
false
true
false
true
false

The recursive function descends into arrays and compares everything else with Object.is. It reports the plain objects in the last example as different, because objects are compared by identity at the leaves. For arrays that hold objects, you need a comparison that goes into objects as well, and the next function does it.

A built-in deep comparison

Node.js ships one in node:util, and the node:assert module has the same logic.

JavaScript
import { isDeepStrictEqual } from "node:util";

console.log(isDeepStrictEqual([1, { a: [2, 3] }], [1, { a: [2, 3] }]));
console.log(isDeepStrictEqual([1, 2], [2, 1]));
console.log(isDeepStrictEqual([NaN], [NaN]));
console.log(isDeepStrictEqual(["1"], [1]));
console.log(isDeepStrictEqual([{ a: 1, b: 2 }], [{ b: 2, a: 1 }]));
console.log(isDeepStrictEqual([new Date(0)], [new Date(0)]));
console.log(isDeepStrictEqual([new Set([1])], [new Set([1])]));
Text
true
false
true
false
true
true
true

isDeepStrictEqual compares arrays, objects, dates, sets and maps by content, treats NaN as equal to NaN, ignores the order of object keys, and does not convert types, so "1" and 1 differ. It is the right tool for nested data in Node.js. In a browser, a library such as Lodash with _.isEqual, or a small hand-written function for your data shape, does the same job. assert.deepStrictEqual() throws with a diff when the values differ, which suits tests.

Same items in any order

When order does not matter, compare sorted copies or count occurrences.

JavaScript
const sameMembersSorted = (a, b) => {
  if (a.length !== b.length) return false;
  const byNumber = (x, y) => x - y;
  return sameArray([...a].sort(byNumber), [...b].sort(byNumber));
};

console.log(sameMembersSorted([3, 1, 2], [2, 3, 1]));
console.log(sameMembersSorted([1, 1, 2], [1, 2, 2]));

function sameMembers(a, b) {
  if (a.length !== b.length) return false;
  const counts = new Map();
  for (const value of a) counts.set(value, (counts.get(value) ?? 0) + 1);
  for (const value of b) {
    const count = counts.get(value);
    if (!count) return false;
    counts.set(value, count - 1);
  }
  return true;
}

console.log(sameMembers(["b", "a", "a"], ["a", "b", "a"]));
console.log(sameMembers(["a", "a", "b"], ["a", "b", "b"]));
console.log(sameMembers([NaN, 1], [1, NaN]));

const original = [3, 1, 2];
[...original].sort();
console.log(original);
Text
true
false
true
false
true
[ 3, 1, 2 ]

Sorting copies, with the spread so the originals are untouched, makes order irrelevant, and a numeric comparator is needed because the default sort compares as text. Sorting is simple and handles numbers and strings, and not mixed or object items. The counting version works for any values a Map can key, handles duplicates correctly, and treats NaN as one key, so [NaN, 1] equals [1, NaN]. Both ignore which positions the items were in. If duplicates do not matter, compare as sets.

Sets and unique items

JavaScript
const sameSet = (a, b) => {
  const left = new Set(a);
  const right = new Set(b);
  return left.size === right.size && left.isSubsetOf(right);
};

console.log(sameSet([1, 2, 2, 3], [3, 2, 1]));
console.log(sameSet([1, 2], [1, 2, 3]));
console.log(sameSet([], []));
Text
true
false
true

Converting to sets removes duplicates and order, so [1, 2, 2, 3] equals [3, 2, 1] here. This is the right question for tags, permissions and ids, where repeats carry no meaning. The isSubsetOf method on sets is available in Node.js 22 and later and in current browsers. On older runtimes, replace it with [...left].every((value) => right.has(value)).

Floating-point values and tolerance

JavaScript
const nearlyEqual = (a, b, epsilon = 1e-9) =>
  a.length === b.length && a.every((value, index) => Math.abs(value - b[index]) <= epsilon);

console.log(sameArray([0.1 + 0.2], [0.3]), nearlyEqual([0.1 + 0.2], [0.3]));
console.log(nearlyEqual([1, 2, 3], [1, 2, 3.0000000001]), nearlyEqual([1, 2], [1, 3]));
Text
false true
true false

Arithmetic on decimals produces tiny errors, so exact comparison of computed numbers is fragile: 0.1 + 0.2 is 0.30000000000000004, and sameArray calls it different from 0.3. A comparison with a tolerance is the practical answer for measurements and results of calculations. The tolerance is a choice: here it is one billionth, so the difference of about 1e-10 in the second call is accepted, and [1, 2] against [1, 3] is not. Pick a tolerance that fits your numbers, and prefer integers for money.

A mistake we hit: sorting the originals

JavaScript
const a = [3, 1, 2];
const b = [2, 3, 1];

const equalIgnoringOrder = (x, y) => sameArray(x.sort((p, q) => p - q), y.sort((p, q) => p - q));

console.log(equalIgnoringOrder(a, b));
console.log(a, b);
Text
true
[ 1, 2, 3 ] [ 1, 2, 3 ]

The comparison was right and changed both arrays, because sort() works in place. A function that was supposed to answer a question had reordered the caller's data, and a later step that depended on the original order, a list shown to a user, came out sorted. Sort copies, with [...x] or toSorted(), in any comparison function.

Choosing between the methods

You wantUse
Same items, same order, primitivesa.length === b.length && a.every((v, i) => v === b[i])
The same, with NaN matchingevery with Object.is
Nested arrays and objectsisDeepStrictEqual from node:util, or _.isEqual
Same items in any order, with duplicatesSorted copies, or a count Map
Same unique itemsCompare as Set objects
Numbers that came from calculationsA comparison with a tolerance
In a testassert.deepStrictEqual(a, b)

Practical rules we follow

Check lengths first. Use every for flat arrays, and a deep comparison for nested data. Never use JSON.stringify, join or ==. Decide whether order and duplicates matter, and say it in the function name. Sort copies, never the arguments. Use a tolerance for floating-point results. And write one test with NaN, one with nested data and one with duplicates.

Where these comparisons stop

Functions in arrays are compared by identity, since two functions with the same source are different values. Objects with cycles need a comparison that tracks visited pairs, and isDeepStrictEqual handles them. Class instances are compared by prototype as well as by fields in the strict version. And very large arrays are compared in linear time, which is the best any content comparison can do. The reference is in the Node.js util.isDeepStrictEqual documentation and the MDN Array.prototype.every page.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.