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]

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

JS Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To
  6. Array Object
  7. Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog