Simplest way to compare two numbers array in JS

Simplest way to compare two numbers array in JS

How to check if two number array contains same elements

·

2 min read

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

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

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

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