DEV Community

How to compare two arrays in javascript?

Marco Pestrin on December 01, 2020

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 = ["s...
Collapse
 
joshinat0r profile image
joshinat0r • Edited

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)

JSON.stringify(serviceList.sort()) === JSON.stringify(botType.sort())
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stereobooster profile image
stereobooster

Why do sort though? Those are not the same arrays [1, 2], [2, 1].

Collapse
 
joshinat0r profile image
joshinat0r

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.

Thread Thread
 
stereobooster profile image
stereobooster

JSON.stringify([undefined]) === JSON.stringify([null])

Thread Thread
 
joshinat0r profile image
joshinat0r

It's just creating two JSON strings and compares them, all of JSONs limitations (not only undefined or null but also Infinite, NaN, functions, symbols and such) apply. Shouldn't have to mention it as should be fairly obvious.

Collapse
 
qmenoret profile image
Quentin Ménoret

This is not working:

let botType = [1,2,3]
let serviceList = [1,1,1]
botType.length === serviceList.length && serviceList.length > 0 && serviceList.every(item => botType.indexOf(item) > -1)
// true
Enter fullscreen mode Exit fullscreen mode

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:

botType.length === serviceList.length && serviceList.length && serviceList.every((element, index) => botType[index] === element)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stereobooster profile image
stereobooster
x = [1,2]
y = [1,2]
x.every(item => y.indexOf(item) > 1)
// false
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pestrinmarco profile image
Marco Pestrin

the condition is > -1

Collapse
 
stereobooster profile image
stereobooster • Edited
x = [1,2]
y = [2,1]
x.every(item => y.indexOf(item) > -1)
// true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pretaporter profile image
Maksim

You can make a bit improvement

botType.indexOf(item) > 1 => botType.includes(item)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
stereobooster profile image
stereobooster • Edited

This will make code work, but it is O(n^2) (the same as the original code)

Collapse
 
nahinakbar profile image
Nahin Akbar

You can use the 'fast-deep-equal' library.
npmjs.com/package/fast-deep-equal

Collapse
 
pestrinmarco profile image
Marco Pestrin

for just 1 check is not good to use a library. A library have other functions that are included but not used