DEV Community

Cover image for Simplest way to compare two numbers array in JS
Shuvo
Shuvo

Posted on

Simplest way to compare two numbers array in JS

In case of string we can simply use == or === to see if they are same but we can't use those to see in two arrays are similar or in other words they have same elements.
So this wont work.

const array1 = [1, 2, 3, 4, 5]
const array2 = [1, 2, 3, 4, 5]
console.log(array1 == array2) //false
Enter fullscreen mode Exit fullscreen mode

But what if we convert our array to string? Then you can use the comparison operator. This makes the task very easy. We can sort an array using toString method eg. array1.toString() or we can use this hack

console.log([1, 2, 3, 4, 5] + "")
//logs 1,2,3,4,5
console.log(typeof ([1, 2, 3, 4, 5] + ""))
//logs string
Enter fullscreen mode Exit fullscreen mode

So basically if we try to concatenate string(empty string in this case) to an array the array will be converted to a string.
so now we can simply use the arrays as strings and compare them

const array1 = [1, 2, 3, 4, 5]
const array2 = [1, 2, 3, 4, 5]
console.log(array1 + "" == array2 + "") //true
Enter fullscreen mode Exit fullscreen mode

Also if you want it to work with arrays where the elements are not in order you can first sort them. Let's create a utility function for that

function compareArr(arr1, arr2){
    arr1.sort()
    arr2.sort()
    return arr1 + "" == arr2 + ""
}
const array1 = [1, 2, 3, 4, 5]
const array2 = [1, 5, 2, 4, 3]
console.log(compareArr(array1, array2)) // returns true
Enter fullscreen mode Exit fullscreen mode

Latest comments (52)

Collapse
 
killshot13 profile image
Michael R.

Ahh! I love the smell of a lively Javascript debate thread in the morning, now to peruse (creep) on all the comments whilst remaining quiet as a church mouse. 😅😁😶

Collapse
 
0shuvo0 profile image
Shuvo

I also should've done that

Collapse
 
joeattardi profile image
Joe Attardi

Please don't ever do this in production code.

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.

Collapse
 
jdforsythe profile image
Jeremy Forsythe

Your function mutates the arrays. After calling compareArr(), array2 will have been sorted. You should copy the arrays before sorting so you don't mutate the parameters

Collapse
 
j7222 profile image
J7222 • Edited

let x=['1',2,5,6];
let y= [1,2,5,6];
let xlenx = x.length;
for(let i=0;i<xlenx;i++){
if(x[i]==y[i]){

console.log(x[i] + ' == ' + y[i])
}
else if(x[i]!==y[i]){
console.log('not same');
break;
}}

Collapse
 
capscode profile image
capscode

There is one amazing Library called underscore to object comparison

Collapse
 
jt3k profile image
Andrey Gurtovoy • Edited
compareArr = (arr1, arr2) => {
  if(arr1.length !== arr2.length){ return false;}
  return arr1.every((item, index) => item === arr2[index]);
};
Enter fullscreen mode Exit fullscreen mode

// Is better for your task

Collapse
 
tamusjroyce profile image
tamusjroyce

Check the length first. That is the simplest way to tell they may not be equivalent. You have also just sorted the original array1 and array2. ‘[…array2].sort()’ would be better.

array1.length === array2.length && array1.some???

Collapse
 
planet_cbx profile image
Charlène Bonnardeaux

I don't think that's a good practice, only because two arrays may contain the same thing but not in the same order... I would tend to just iterate on one and do a comparison with each of the values

Collapse
 
blackr1234 profile image
blackr1234

If order matters, don't sort them before converting to strings. Yeah of course you could loop them, or use utility libraries.

Collapse
 
coderduck profile image
duccanhole

but if we compare [1,'2',3] and [1,2,3]; I expect false, and result is true

Collapse
 
0shuvo0 profile image
Shuvo

yes that's why in the post title I said numbers array

Collapse
 
lexlohr profile image
Alex Lohr

A faster way of unsorted equality would be:

const arrayEqualsUnsorted = (array1, array2) =>
  array1.length === array2.length && 
  array1.every(item => array2.includes(item));
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hnicolas profile image
Nicolas Hervé

It don"t work with duplicated values.

arrayEqualUnsorted([1, 1, 2], [1, 2, 2]); // true
Enter fullscreen mode Exit fullscreen mode
Collapse
 
hongphuc5497 profile image
Hong Phuc

You should remove duplicated items with Set class first before comparing, for example:

const uniqueArr = [... new Set(yourArr)]