JavaScript: Compare Array Equality

By Xah Lee. Date: . Last updated: .

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

console.log([3, 4] === [3, 4]); // false
const x = [3, 4];
const y = [3, 4];
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, because array element may be object, and there key may have different order.

// array comparison by JSON.stringify is not reliable
const x = [4, { "a": 1, "b": 2 }];
const y = [4, { "b": 2, "a": 1 }];
console.log(JSON.stringify(x) === JSON.stringify(y)); // false

Compare Array by Comparing Every Element

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

Test Equality of Objects

JavaScript Array

βˆ‘ JS in Depth
XAH Β BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc