const a = [1,2,3] const b = [1,2,3] a === b //false
A very common solution that many people suggest is to use
JSON.stringify(). This makes us able to serialize the two arrays and compare them as Strings.
an Implementation will look like this
const equals = (a, b) => JSON.stringify(a) === JSON.stringify(b); const a = [1, 2, 3]; const b = [1, 2, 3]; equals(a, b); // true
this is seems like a great solution but there is some edge cases where different values serialized string is the same. for example
null === undefined; // false equals([null], [undefined]); // true, should be false
these may cause some annoying Issues that are hard to track down and fix.
A better way is to compare the length of the arrays and then every element using the
here is an Implementatoin of this Approach
const equals = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]); const a = [1, 2, 3]; const b = [1, 2, 3]; const str = 'a'; const strObj = new String('a'); equals(a, b); // true equals([str], [strObj]); // false equals([null], [undefined]); // false
You like our Content? Follow us to stay up-to-date.