JS: Test Array Equality 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 got several problems, such as array involving undefined or sparse array. But even so, it is extremely inefficient. Do not do this for array with lots items or in a loop.
Problem: undefined vs null
JSON string converts undefined to null.
// json convert undefined to null console.assert(JSON.stringify([undefined, 5]) === JSON.stringify([null, 5]));
Problem: sparse array
// these 2 arrays are not same const aa = [1, , 3]; const bb = [1, undefined, 3]; console.assert((Reflect.ownKeys(aa) === Reflect.ownKeys(bb)) === false); // but in json they are the same console.assert((JSON.stringify(aa) === JSON.stringify(bb)) === true);
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 console.assert(JSON.stringify([4, 5, 6]) === JSON.stringify([4, 5, 6]));
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 const aa = [4, [4, 5, 6], 6]; const bb = [4, [4, 5, 6], 6]; console.assert(JSON.stringify(aa) === JSON.stringify(bb)); // example of diff order. should be false const cc = [4, [4, 6, 5], 6]; const dd = [4, [4, 5, 6], 6]; console.assert((JSON.stringify(cc) === JSON.stringify(dd)) === 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
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));