Some days ago I needed to compare two arrays in Javascript and I trivially tried to compare them as if they were strings
const serviceList = ["sales_bot"]
const botType = ["sales_bot"]
console.log(serviceList == botType)
and the result was this:
false
It is possible to compare arrays using the "every" method in javascript. A possible solution is
botType.length === serviceList.length && serviceList.every(item => botType.indexOf(item) > -1)
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:
botType.length === serviceList.length && serviceList.length > 0 && serviceList.every(item => botType.indexOf(item) > -1)
Enjoy your code mates!
Top comments (13)
I like to abuse JSON if I just want to know if they have the exact same entries (when I know that they arrays are fairly small since JSON.stringify isn't exactly fast)
Why do sort though? Those are not the same arrays
[1, 2]
,[2, 1]
.Semantics,
[1, 2]
and[2, 1]
have the same entries but aren't the same arrays.You're right, if you wanted to know if they have the same entries in the same order you wouldn't sort them.
JSON.stringify([undefined]) === JSON.stringify([null])
It's just creating two JSON strings and compares them, all of JSONs limitations (not only
undefined
ornull
but alsoInfinite
,NaN
, functions, symbols and such) apply. Shouldn't have to mention it as should be fairly obvious.This is not working:
Every element of the second list is in the first list, but they are definitely not equals.
A proper way to do this would be:
the condition is > -1
You can make a bit improvement
This will make code work, but it is
O(n^2)
(the same as the original code)You can use the 'fast-deep-equal' library.
npmjs.com/package/fast-deep-equal
for just 1 check is not good to use a library. A library have other functions that are included but not used