JS: Test Array Equality by Comparison as JSON String
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));
undefined vs null
const aa = [undefined, 5]; const bb = [null, 5]; console.log(JSON.stringify(aa) === JSON.stringify(bb)); // true // should be false
Sparse array
// these 2 arrays are not same const aa = [1, , 3]; const bb = [1, undefined, 3]; console.log((Reflect.ownKeys(aa) === Reflect.ownKeys(bb)) === false); // true // but in json they are the same console.log(JSON.stringify(aa) === JSON.stringify(bb)); // true
Test Equality of Nested Arrays 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);
JSON cannot be used to test equality of objects
🛑 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);
Test Equality of Arrays-Like Objects
best thing to do on Arrays-Like Objects, is to turn them into true array first.
use Array.from.
JS: Array.from
but for curiosity, here's analysis.
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));