How to compare two arrays in javascript?

Marco Pestrin
1 min readNov 29, 2020

Some days ago I needed to compare two arrays in Javascript and I trivially tried to compare them as if they were strings

and the result was this:

It is possible to compare arrays using the “every” method in javascript. A possible solution is:

I started with length arrays comparison, to be sure to have the same items. Then, I needed to check if the items were inside the same number of times.

It is essential that the first condition is satisfied at first, since it is less elaborate than the second one. Indeed, the second condition has to cycle every element of the array.

If the first returns FALSE, then the second one won’t even be executed. Therefore we are sure that the arrays will be different because they have different numbers of elements.

If the first returns TRUE, is to check even the second condition. This means to check that all the elements of arrays are actually the same

How is this comparison done?

The every method returns true just if all elements satisfy the condition and the indexOf method return the index of element. If doesn’t exist the result is -1. For this reason the condition is > -1

In this case, I knew for sure that one of my array would have never been empty, otherwise the problem would have been somewhere else. It happens other times that this thing is not obvious and then you need one more check like the following:

Enjoy your code mates!

--

--