Comparing two arrays is one of the widely used and most important challenges you might face in programming. There are many ways to do this, but we are going to learn the easiest and fastest ways.
1. Using loops
Of course, the first way would be looping. We can quickly compare array elements one by one. No matter whether it is a "while" loop or a for
loop. First, we need to check the length of the two arrays. If both have the same size, we can keep the comparison up.
function compareTwoArrays(arr1, arr2) {
if (arr1.length !== arr2.length)
return false;
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i])
return false;
}
return true;
}
compareTwoArrays([null, 1, 2], [undefined, 1, 2])
Now, let's test our function. We are going to pass two arrays that are different:
let array1 = [null, 1, 2];
let array2 = [undefined, 1, 2];
compareTwoArrays(array1, array2) // false
As we expect, it returns false, because null
is not equal to undefined
Then, let's pass two arrays that are exactly the same:
let array3 = [null, 1, "a"];
let array4 = [null, 1, "a"];
compareTwoArrays(array3, array4) // returns true
This time, it returns true.
2. Using every() method
What does the every()
method do? The every()
method executes a function for every array element. So we can use it instead of loops. The every() method returns a boolean, and we will return the result as the result of the function. If all the elements of two arrays are equal at the same index, it returns true, otherwise returns false.
function compareTwoArrays(arr1, arr2) {
if (arr1.length !== arr2.length)
return false;
return arr1.every((element, index) => {
return element === arr2[index]
});
}
let array1 = [null, 1, "a"];
let array2 = [null, 1, "a"];
compareTwoArrays(array1 , array2); // true
And the result will be the same as before.