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 and Properties

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

〔➤see JavaScript: Understand JS Array

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.