DEV Community

Discussion on: Simplest way to compare two numbers array in JS

Collapse
 
valeriavg profile image
Valeria

This method will not work for non-primitive values:

[{v:1},{v:2},{v:3}] + ''
// '[object Object],[object Object],[object Object]'
Enter fullscreen mode Exit fullscreen mode

Although slight alteration to the algorithm will do the trick:

JSON.stringify([{v:1},{v:2},{v:3}])
// '[{"v":1},{"v":2},{"v":3}]'
JSON.stringify([1,2,3,4,5])
// '[1,2,3,4,5]'
Enter fullscreen mode Exit fullscreen mode

However even the latter comparison is aimed for simple and small arrays as it can be pretty expensive and yield unexpected results for some edge-cases, e.g.:

JSON.stringify(new Set([1,2,3]))
// '{}'
Enter fullscreen mode Exit fullscreen mode

In those cases one can use deep equal implementation from a variety of packages.

Collapse
 
0shuvo0 profile image
Shuvo

true, most short hacks usually have drawbacks

Collapse
 
ksengine profile image
Kavindu Santhusa

Your solution has too many drawbacks.

Thread Thread
 
pierrewahlberg profile image
Pierre Vahlberg

That was not very constructive really. Care to explain a bit what the drawbacks could be?

Collapse
 
suckup_de profile image
Lars Moelleken • Edited

Last time I needed to compare sommeting in JS I used "JSON.stringify" but its still a hack. What is the correct way to do it nowadays? 🤔

Collapse
 
0shuvo0 profile image
Shuvo

Writing an algorithm with loop and recursion if needed

Thread Thread
 
ksengine profile image
Kavindu Santhusa

Extractly

Collapse
 
valeriavg profile image
Valeria

There is no general right or wrong as it depends on a particular use case, but if you want an optimal solution that would handle most of the cases it'll probably be a recursive iterator over indices with early return.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

This method will not work for non-primitive values

I read that as "non-prime values" at first and was severely confused 😆

Collapse
 
wxs77577 profile image
Johnny Wu

also you can use lodash.isMatch _.isMatch