Simplest way to compare two numbers array in JS

Shuvo - Oct 18 '21 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .