JavaScript: Test Array Equality

By Xah Lee. Date: . Last updated: .

Test Array Equality by Comparing Every Element

Array Are Equal If Their References Are the Same

JavaScript considers array to be equal only if their reference are the same. (not their contents)

// 2 array having same reference. comparison return true
const xx = [3, 4];
const yy = xx;
console.log(xx === yy);
// 2 array having same content. comparison return false
const xx = [3, 4];
const yy = [3, 4];
console.log((xx === yy) === false);

There's no builtin way to test array items equality in JavaScript.

Test Array Equality by Comparison as JSON String

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

WARNING: This is extremely inefficient. Do not do this for array with lots items.

Test Equality of Flat Arrays by Converting to JSON

If arrays are flat (no nesting), then one convenient way to test equality is by converting them to JSON.

// test equality of flat arrays by JSON.stringify
const aa = [4, 5, 6];
const bb = [4, 5, 6];
console.log(JSON.stringify(aa) === JSON.stringify(bb));

Test Equality of Nested Arrays (No Objects) by Converting to JSON

Equality of content of nested true arrays can also be tested by first converting them to JSON.

// test equality of nested arrays by JSON.stringify
const aa = [4, [4, 5, 6], 6];
const bb = [4, [4, 5, 6], 6];
console.log(JSON.stringify(aa) === JSON.stringify(bb));

// example of diff order, result false
const xx = [4, [4, 6, 5], 6];
const yy = [4, [4, 5, 6], 6];
console.log((JSON.stringify(xx) === JSON.stringify(yy)) === false);

Test Equality of of Arrays-Like Objects

Equality of content of flat Array-Like Objects can also be tested by first converting them to JSON.

// test equality of non-nested array-like objects by JSON.stringify

const aa = { 0: "a", 1: "b", length: 2 };
const bb = { 0: "a", 1: "b", length: 2 };
console.log(JSON.stringify(aa) === JSON.stringify(bb));
// it's ok if order are not the same, since they are still considered array-like objects
const xx = { 1: "b", 0: "a", length: 2 };
const yy = { 0: "a", 1: "b", length: 2 };
console.log(JSON.stringify(xx) === JSON.stringify(yy));

Test Equality of Arrays with Nested Objects. No

WARNING: comparison array with nested object as json string doesn't work, because array element may be object, and their keys may have different order.

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

JavaScript Array

BUY
Ξ£JS
JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Property

Object and Inheritance

Array

Function

Constructor/Class

Iterable 🌟

Misc