Comparing Arrays in JavaScript

Wouldn’t it be great if you could just compare two arrays like this:

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:

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!

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!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store