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...
For further actions, you may consider blocking this person and/or reporting abuse
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
undefinedornullbut 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 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
You can make a bit improvement
This will make code work, but it is
O(n^2)(the same as the original code)