JS: Compare Array Equality

By Xah Lee. Date: . Last updated: .

There's no builtin way to compare array in JavaScript.

You can see in the following examples, simple comparison will fail.

console.log( [3,4] === [3,4] ); // false
console.log( [3,4] == [3,4] );  // false
const x = [3,4];
const y = [3,4];

console.log( x === y ); // false
console.log( x == y );  // false

Compare as JSON String, Not Reliable

One workaround of comparing array is to convert them into JSON string then compare the string.

WARNING: comparison array as json string is not reliable. One reason it'll fail is when it contain objects, because object's properties do not have a well-defined order.

// array comparison by JSON.stringify is not reliable

const x = [4, {"a":1, "b":2}] ;
const y = [4, {"b":2, "a":1}] ; // reverse order

console.log( JSON.stringify(x) === JSON.stringify(y) ); // false

[see JS: JSON Object]

Compare Array by Comparing Every Element

For a function that compare any 2 objects by deep diving and compare their elements, see:

JS: Test Equality of Objects

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth