DEV Community

Discussion on: How to compare two arrays in javascript?

Collapse
joshinat0r profile image
joshinat0r • Edited on

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.