DEV Community

Carlos Nah
Carlos Nah

Posted on

Comparing Arrays using isArrayEquals() method

JavaScript is a great language that has endured a long struggle over the years. Yet it continues to shine despite all the criticisms.

In this regard, I have decided to compare two arrays and see if they are equal. Equal in the sense of length and element within the array. In so doing I also take into consideration that the order of the elements doesn't matter.

Here is my code below:

 const isArrayEquals = (arr1, arr2) => {
     let count = 0;
     for(let i = 0; i < arr1.length; i++) {
        for(let j = 0; j < arr2.length; j++) {
           if(arr1[i] == arr2[j]) {
                count++
           }
     }   
 }

 return  arr1.length == arr2.length && count == arr1.length ? true : false;
}


console.log(isArrayEquals([1, 2, 3, 4, 5], [1, 2, 5, 3, 4])) // true
console.log(isArrayEquals(["me", "you", "us"], ["us", "me"])) // false
console.log(isArrayEquals([], [])) // true
Enter fullscreen mode Exit fullscreen mode

Well this might not be the best way to implement this but I think it will help in the process.

I've also implemented this and some other helper methods into a npm package called rademe-js.

Hope it helps and someday we might have Array.equals implemented into ECMA TC39 specification.

Discussion (8)

Collapse
harrison_codes profile image
Harrison Reid

This looks like a clean implementation for most use cases! One limitation is that I don't think it will handle equality comparisons where the array elements are themselves arrays or objects. For example:

console.log(isArrayEquals([{}, {}], [{}, {}]) // false
console.log(isArrayEquals([[], []], [[], []]) // false

Collapse
ra9 profile image
Carlos Nah Author • Edited on

Thanks @Harrison Reid, at first my thoughts weren't focus on this aspect and now I will have to look into it and see what needs to be done.
And if you have a solution to share I will be grateful.

Collapse
harrison_codes profile image
Harrison Reid

I don't have any solution to share for the moment unfortunately, I don't think it's an easy problem to solve - particularly when considering deeply nested combinations of arrays and objects.

Thread Thread
ra9 profile image
Carlos Nah Author

Yeah sure but I do believe it can be solve.
Anything is possible

Thread Thread
harrison_codes profile image
Harrison Reid

Absolutely! Good luck with it 👍

Collapse
avalander profile image
Avalander

Why would you consider two arrays with the same elements in different order equal?

Collapse
thefern profile image
Fernando B 🚀

could have been sorted, or just appended in a different order.

Collapse
ra9 profile image
Carlos Nah Author

Yeah well, I think it doesn't matter which order it is in what should matters is if the elements in those arrays are the same.