JS: Problems of testing array equality as json string
JavaScript does not have a builtin way to test the equality of two array's contents.
one workaround is to convert arrays into JSON string then compare the string.
This got several problems, we list on this page. Also note it is extremely inefficient. Do not do this for array with hundreds of 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), );
Problem: objects in array
// two arrays, each contains an object. // the object contents are the same, but in different order. // if compared as json, result is false. const xx = [4, { "a": 1, "b": 2 }]; const yy = [4, { "b": 2, "a": 1 }]; console.assert((JSON.stringify(xx) === JSON.stringify(yy)) === false);