How To Compare Two Arrays In JavaScript

To compare two arrays in JavaScript –

  1. Check if the length of both the arrays is same.
  2. If length of the two arrays is not same, return false.
  3. If the length of the two arrays is same, use Array.every() method on the first array to check if all elements in it are equal to the corresponding element of the second array at the same index. If both arrays contain identical values for every corresponding index, then return true, otherwise return false.

Let’s discuss this method in detail below.

how to compare two arrays in javascript

How To Compare Two Arrays In JavaScript?

In order to compare two arrays in JavaScript, we need to check if the length of both the arrays is same. If the length of the two arrays is not same, that means the arrays are not equal and we can return false immediately.

If the length of the two arrays is same, then we use Array.every() method on the first array to check if all elements in it are equal to the corresponding element of the second array at the same index. If both arrays contain identical values for every corresponding index, then return true, otherwise return false.

The Array.every() method executes the provided callback function once for each element present in the array until it finds an element where callback returns a falsy value.

callback is invoked with three arguments:

  1. the value of the element
  2. the index of the element
  3. the Array object being traversed

Let’s see an example of how to compare two arrays in JavaScript.

Example:

In this example, we have two arrays arr1 and arr2 which contain some random integers. We are comparing both the arrays using Array.every() method.

If both the arrays contain same values at each index, then it will return true, otherwise it will return false.

arr1 = [-1, 0, 1];

arr2 = [-1, 0, 1];

function compareArrays(arr1, arr2) {

if(arr1.length !== arr2.length) {

  return false;

}

return arr1.every((element, index) => {

   return element === arr2[index];

});

}

console.log(compareArrays(arr1, arr2)); // true

In the above example, both arrays arr1 and arr2 contain same values at each index. So, it will return true.

Now, let’s see another example where both arrays do not contain same values.

arr1 = [-1, 0, 1];

arr2 = [-1, 0, 2];

function compareArrays(arr1, arr2) {

if(arr1.length !== arr2.length) {

   return false;

}

return arr1.every((element, index) => {

    return element === arr2[index];

});

}

console.log(compareArrays(arr1, arr2)); // false

In the above example, both arrays contain different values at index 2. So, it will return false.

That’s it. These are the two ways to compare two arrays in JavaScript. I hope you find this article helpful. Thanks for reading! 🙂

Leave a Reply