DEV Community

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

Collapse
 
0shuvo0 profile image
Shuvo

Agreed

Collapse
 
joeattardi profile image
Joe Attardi

So you agree that your own post is a bad idea? 🤔

Thread Thread
 
0shuvo0 profile image
Shuvo

yes there is always drawbacks of easy hacks.
But if you're confident about your input you might as well ues this

Thread Thread
 
joeattardi profile image
Joe Attardi

Sometimes hacks make it into production code and become technical debt. This is not a hack that should ever be in a real application.

There are a lot of beginners on DEV and when they see posts like this it teaches them really bad practices. Particularly here since you have tagged it with #beginners.

Besides, your "solution" is for comparing arrays of numbers only. Comparing two arrays containing just numbers is easy with a simple loop since there aren't nested properties, etc.

function arrayEquals(arr1, arr2) {
  for (let i = 0; i < arr1.length; i++) {
    if (arr1[i] !== arr2[i]) {
      return false;
    }

    return true;
}
Enter fullscreen mode Exit fullscreen mode

You could also use Array.prototype.every for a one-liner:

function arrayEquals(arr1, arr2) {
  return arr1.every((el, index) => arr2[index] === el);
}
Enter fullscreen mode Exit fullscreen mode

With both of the above approaches, it bails out as soon as it finds two array elements that are not unique. Stringifying and comparing strings (yuck) requires processing each array in full.