Comparing Arrays in JavaScript
Wouldn’t it be great if you could just compare two arrays like this:
[1,2,3] === [1,2,3]
That would be great! But unfortunately, it can’t be done because arrays are actually objects in javascript. Primitive types can be compared by their value in javascript, like strings and integers. However objects are more complex types and are compared by their reference, or place they are stored in memory. So every time an object is created, it is given a reference to a space where it is stored. So, even though an object may look identical, its reference is not.
So what does this mean for us, when we are trying to compare two arrays?
It means that we can’t just compare them point blank like we tried to above. We will need to look at each individual item in the array and compare it to each individual item of the other array.
When comparing two arrays, the easiest way to know if they are not the same is to compare their lengths. So we start by building out our method likes so:
function compareTwoArrays(arr1, arr2) {
if (arr1.length === arr2.length) {
return false
}
}
If this is true, our arrays are most definitely not identical and we can exit out of our function and return false
.
The next thing we want to look for is if each item in arr1
equals each item in arr2
. For this we will need to iterate over our arrays and compare each item, which in our case are integers and integers are primitive types in javascript and can be compared!
function compareTwoArrays(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false
} else {
for (let i = 0; i < arr1.length; i++){
if (arr1[i] !== arr2[i]){
return false
} else {
continue
}
}
}
return true
}
If our the number at arr1[i]
does not equal the number at the same index of arr2
we know that this is not a match and therefore we return false
and break out of our loop. If it is a match, we continue on through our iteration to the next index. Once i
is not longer less than the length of our array and our if
statement never equates to true
, we end our loop and continue to the last line of our function and return true
.
So, this is not as simple as just using the ===
operator, but it gets the job done!