Explain Codes LogoExplain Codes Logo

How to compare arrays in JavaScript?

javascript
prompt-engineering
best-practices
performance
Alex KataevbyAlex Kataev·Feb 15, 2025
TLDR

For straightforward array comparison, try this simple line of code:

const arraysMatch = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);

Usage is incredibly straightforward:

console.log(arraysMatch([1, 2], [1, 2])); // true

This checks if both arrays are the same length and have identical elements at each index. However, the plot thickens with nested arrays or objects.

Advanced scenarios

Taming dragons (nested arrays)

For dealing with these so-called dragons (nested arrays), consider a recursive approach:

// Dragon slayer algorithm. Doesn't really slay dragons. const compareNestedArrays = (a, b) => { // Dragon equals dragon. Easy peasy. if (a === b) return true; // No dragons here. Sorry. if (a == null || b == null || a.length !== b.length) return false; // Time for the epic dragon showdown. for (let i = 0; i < a.length; i++) { if (Array.isArray(a[i]) && Array.isArray(b[i])) { // Recursive dragon slaying. Not for the squeamish. if (!compareNestedArrays(a[i], b[i])) return false; } else if (a[i] !== b[i]) { return false; } } // We got to the end without returning false. Hooray! return true; };

When comparing apples and oranges (objects)

For handling these tricky nonconformists (objects), some tailored object logic:

// Preparation for the epic showdown. const objectsMatch = (obj1, obj2) => // Counts the number of chickens before they hatch. Also checks if eggs are of the same kind. Object.keys(obj1).length === Object.keys(obj2).length && Object.keys(obj1).every(key => obj2.hasOwnProperty(key) && obj1[key] === obj2[key]); // The epic showdown. Apple vs Orange. Who will win? const arraysOfObjectsMatch = (a, b) => a.length === b.length && a.every((obj, index) => objectsMatch(obj, b[index]));

The mighty Lodash in shining armor

For downright Thor's hammer Mjölnir-like smashing of both objects and arrays, Mjölnir of JavaScript (lodash) got your back:

// Summoning Mjölnir of lodash. const deepEqual = require('lodash.isequal'); console.log(deepEqual([1, { a: 2 }], [1, { a: 2 }])); // Thor smashes it! true

Best practices for the wise and learned

Quick draw McGraw (length check)

A quick draw of your length checking pistol might save you from an embarrassing shootout:

// McGraw's quick draw technique. if (a.length !== b.length) return false; // They ain't the same if they ain't the same size.

Order in chaos (sorting)

If marching order doesn't matter, make 'em salute and sort:

// Line 'em, count 'em, match 'em. const arraysMatchUnordered = (a, b) => a.length === b.length && a.sort().every((v, i) => v === b.sort()[i]);

JSON.stringify isn't your grandma

Even though your grandma might talk a lot, JSON.stringify() talks even more:

// Granny chatterbox way. Talks a lot, but can forget the order. // Unless she takes her memory pills (sorting before stringify). const arraysAreEqual = JSON.stringify(a) === JSON.stringify(b);

Edge cases, quirks, and coffee shortages

When searching turns into hide and seek (indexOf)

A classic game of hide and seek might be necessary if you're trying to locate particular elements:

// Classic game of hide and seek. const contains = (arr, element) => arr.indexOf(element) !== -1;

When things aren't too primitive for you

When comparing non-primitive elements (like that fancy coffee maker you bought last week), direct comparison can't simply cut it. Take a look at the manual (understand the logic) and proceed.

Think before you plunge

When ambushing comparison functions, mind the performance implication. Native operations are reliable comrades, while recursive calls can quickly turn into a barrel of monkeys.