Check if Two Arrays have Same Elements in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if Two Arrays have the Same Elements #

To check if two arrays have the same elements:

  1. Check if the arrays have the same length.
  2. Use the every() to check if the arrays contain the same element at the same index.
  3. The every method only returns true if the condition is met for all array elements.
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 passed 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 in 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 returning false.

The areEqual function only returns true if the passed in arrays have the same length, 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 in 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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.