JavaScript: Array Compare Equality

JavaScript: Array Compare 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
var x = [3,4];
var 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

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

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

〔►see JavaScript: JSON Object

Compare Array by Comparing Every Element

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

JavaScript: Test Equality of Objects

Array Topic

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

  1. JavaScript: Array Object
  2. JavaScript: Array.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.