Check if Two Arrays have Same Elements in JavaScript

avatar

Borislav Hadzhiev

Sat Oct 16 20212 min read

banner

Photo by Jake Melara

Check if Two Arrays have the Same Elements #

To check if two arrays have the same elements:

  1. Verify that the arrays have the same length.
  2. Call the every() method on the first array and verify that the element on every iteration is equal to the element at the same index from the other array.
  3. The every method only returns true if the condition is met for every array element.
index.js
const arr1 = ['a', 'b', 'c']; const arr2 = ['a', 'b', 'c']; function areEqual(array1, array2) { if (array1.length === array2.length) { return array1.every((element, index) => { if (element === array2[index]) { return true; } return false; }); } return false; } console.log(areEqual(arr1, arr2)); // ๐Ÿ‘‰๏ธ true

We first check if the arrays have the same length, if they don't, we return false straight away.

The function we pass to the Array.every method gets invoked with each element in the array until it returns a falsy value or iterates over the entire array.

On each iteration, we check if the current element is equal to the element at the same index from the other array.

The every method returns true, only if the test function returns a truthy value on all iterations, otherwise it returns false.

If the test function returns false, the every method short-circuits and returns false.

The areEqual function only returns true if the passed in arrays have the same length and their values are equal and in the same order.

In this example, we call the areEqual function with two arrays containing the same elements in a different order and the function returns false.

index.js
const arr1 = ['c', 'b', 'a']; const arr2 = ['a', 'b', 'c']; function areEqual(array1, array2) { if (array1.length === array2.length) { return array1.every((element, index) => { if (element === array2[index]) { return true; } return false; }); } return false; } console.log(areEqual(arr1, arr2)); // ๐Ÿ‘‰๏ธ false

If you don't care about the ordering of the elements and you just want to check if two arrays contain the same elements, use this approach instead.

index.js
const arr1 = ['c', 'b', 'a']; const arr2 = ['a', 'b', 'c']; function areEqual(array1, array2) { if (array1.length === array2.length) { return array1.every(element => { if (array2.includes(element)) { return true; } return false; }); } return false; } console.log(areEqual(arr1, arr2)); // ๐Ÿ‘‰๏ธ true

Instead of checking if the current element is equal to the element of the other array with the same index, we just check if the element is included in the other array.

We know that if the arrays have the same length and each element of one array is contained in the other array, we have 2 equal arrays with possibly different ordering.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee