Check if two arrays are equal in JavaScript
Intermediate · 3 min read
Sooner or later you need to know whether two arrays hold the same values. Has the user changed their selected filters? Did the test produce the expected list? Are these two shopping carts the same? The natural first try, a === b, gives the wrong answer every time, and understanding why is the most useful part of this exercise.
In this tutorial you will write two functions. sameOrder(a, b) checks that the values match position by position. sameContents(a, b) checks that the arrays hold the same values in any order. You need to know what an array and a function are.
Why === doesn't work on arrays
const a = [1, 2, 3];
const b = [1, 2, 3];
console.log(a === b); // false
console.log(a === a); // true
An array is an object. A variable that holds an object doesn't hold the values themselves. It holds a reference, which you can think of as the object's address. === compares the addresses: "are these the very same array?" a and b were created separately, so they live at different addresses, even though their contents match.
So to compare contents, you have to look inside and compare the values one by one.
The every method
every runs a test on each item and returns true only if every item passes. It also gives you each item's position:
console.log([2, 4, 6].every((v) => v % 2 === 0)); // true
console.log([2, 5, 6].every((v) => v % 2 === 0)); // false
console.log(['x', 'y'].every((v, i) => i < 2)); // true: i is the position
Here is the exercise. Try it yourself first if you like, or follow the steps.
27 Check whether two arrays hold the same values
fairDecide whether two arrays contain the same values. Handle order-sensitive and order-insensitive comparison, and explain why === is no use.
Stuck? Three hints, smallest first
- 1. Two arrays are never
===equal, even with identical contents. They are different objects. - 2. For order-sensitive comparison, check the lengths then compare index by index.
- 3. For order-insensitive, sort copies first, or count occurrences with a Map.
Step 1: compare position by position
If the lengths differ, the arrays can't match, so check that first. Then compare each value with the value at the same position in the other array:
function sameOrder(a, b) {
if (a.length !== b.length) return false;
return a.every((v, i) => v === b[i]);
}
console.log(sameOrder([1, 2, 3], [1, 2, 3])); // true
console.log(sameOrder([1, 2, 3], [3, 2, 1])); // false
console.log(sameOrder([1], [1, 2])); // false
console.log(sameOrder([], [])); // true
Why the length check? Without it, sameOrder([1], [1, 2]) would only look at [1]'s single item, find it matches, and say true.
Step 2: ignore the order
To compare contents in any order, sort both arrays first. Then same contents means same order, and Step 1's check works. Here is the tempting version:
function sameContentsBad(a, b) {
if (a.length !== b.length) return false;
a.sort();
b.sort();
return a.every((v, i) => v === b[i]);
}
const c = [3, 2, 1];
console.log(sameContentsBad([1, 2, 3], c)); // true
console.log(c); // [ 1, 2, 3 ]: the caller's array was reordered
The answer is right, but sort() changes the array it is called on. The caller only asked a yes-or-no question, and their array came back rearranged. That kind of bug shows up somewhere else entirely, much later.
Step 3: sort copies instead
[...a] spreads the items into a brand-new array. Sort the copies and leave the originals alone:
function sameContents(a, b) {
if (a.length !== b.length) return false;
const x = [...a].sort();
const y = [...b].sort();
return x.every((v, i) => v === y[i]);
}
const c = [3, 2, 1];
console.log(sameContents([1, 2, 3], c)); // true
console.log(c); // [ 3, 2, 1 ]: untouched
One small note: sort() with no arguments sorts values as text, so 10 comes before 9. For this check that doesn't matter. Both copies are sorted by the same rule, so equal contents still line up.
Step 4: the JSON shortcut
You will often see this:
console.log(JSON.stringify([1, 2, 3]) === JSON.stringify([1, 2, 3])); // true
console.log(JSON.stringify([1, 2, 3]) === JSON.stringify([3, 2, 1])); // false
JSON.stringify turns each array into text, like '[1,2,3]', and comparing two strings does compare their contents. It is quick to write and fine for small arrays of numbers or strings. But it is order-sensitive, it builds two whole strings just to compare them, and some values don't survive the trip into text (undefined inside an array becomes null).
The full solution
The complete answer has both functions, shows === failing on two equal arrays, tries the JSON shortcut, and proves that sameContents leaves its inputs untouched. Press Run to see the output.
// Order matters.
function sameOrder(a, b) {
if (a.length !== b.length) return false;
return a.every((v, i) => v === b[i]);
}
// Order does not matter. Sort copies, never the originals.
function sameContents(a, b) {
if (a.length !== b.length) return false;
const x = [...a].sort();
const y = [...b].sort();
return x.every((v, i) => v === y[i]);
}
const a = [1, 2, 3];
const b = [1, 2, 3];
const c = [3, 2, 1];
console.log('=== on two equal arrays:', a === b);
console.log('sameOrder(a, b) :', sameOrder(a, b));
console.log('sameOrder(a, c) :', sameOrder(a, c));
console.log('sameContents(a, c):', sameContents(a, c));
// The JSON shortcut works but is order-sensitive and slow on big arrays:
console.log('via JSON:', JSON.stringify(a) === JSON.stringify(b));
// sameContents sorts copies, so the inputs are untouched:
sameContents(a, c);
console.log('c after comparing:', c);
Output
7 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 7 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('two arrays are never === equal', a === b, false);
test('same order, same values', sameOrder(a, b), true);
test('different order fails the strict check', sameOrder(a, c), false);
test('but passes the contents check', sameContents(a, c), true);
test('different lengths fail both', sameOrder([1], [1, 2]), false);
test('empty arrays match', sameOrder([], []), true);
test('the inputs were not reordered', c, [3, 2, 1]);
The last assertion is the habit worth keeping. sort() mutates, so a naive a.sort() inside a comparison function quietly reorders the caller's array — a bug that shows up somewhere else entirely. Spreading into a copy first costs one character and removes the whole class of problem.
Common mistakes
- Using
===or==on two arrays. Both compare references, so two separate arrays are never equal. - Skipping the length check. A shorter array can match the start of a longer one and pass.
- Sorting the inputs directly.
sort()reorders the caller's arrays. Sort copies.
Try it yourself
- Use
sameContentsto check whether'listen'and'silent'contain the same letters. (Hint: turn each word into an array first.) - Write
startsWith(a, prefix)that checks whether arrayabegins with the items inprefix. - Try
sameOrder([[1]], [[1]]). Why is itfalse? What would you need to compare arrays inside arrays?