Sometimes can be useful an efficient way to verify that two arrays of objects or primitives are the same. In these cases, the simple comparison operator is not enough because arrays are two different instances of objects. We have to compare js arrays that are lists and not simple objects.
For example the following comparison will give an erroneously wrong result:
[true, false, true, false] == [true, false, true, false] // false
The solution is to first check the length and consistency of both arrays under consideration and then check the objects in them.
First we consider the version suitable for javascript, through a function.
/**
* Compare 2 given arrays.
* @param a1
* @param a2
*/
function compareArrays(a1, a2) {
if (!a1 && !a2 && a1.length !== a2.length) {
return false;
}
return !a1.some((v, i) => (v !== a2[i]));
}
The one below is the typed method (suitable for typescript frameworks: Angular, React, etc.):
/**
* Compare 2 given arrays.
* @param a1
* @param a2
*/
public static compareArrays(a1: any[], a2: any[]): boolean {
if (!a1 && !a2 && a1.length !== a2.length) {
return false;
}
return !a1.some((v, i) => (v !== a2[i]));
}
The result will be the following, using our function to compare js arrays:
compareArrays([true, false, false], [true, false, false]); // true
compareArrays([true, false, false, false], [true, false, false]); // false
compareArrays(['equal', false, false, false], ['equal', false, false, false]); // true
compareArrays(['different', false, false, false], ['equal', false, false, false]); // false
That’s all.
Try it at home!