This page looks best with JavaScript enabled

Check if two arrays are equal in Javascript

 ·   ·  ☕ 1 min read

You can’t just equate arrays - you are smarter than that.

Consider the simple example where we want to compare arrays and test their equality.

1
2
3
const fruits = ["apple", "orange"];
const oldFruits = ["apple", "orange"];
console.log(fruits == oldFruits); // false

It may be obvious in hindsight - but array comparison in the above code will not compare values and give you the expected answer.

Instead you would have to go old school and compare everything within an array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const fruits = ["apple", "orange"];
const oldFruits = ["apple", "orange"];
const newFruits = ["pear", "raspberry"];
const moreFruits = ["pear", "raspberry", "grapes"];

console.log(arrEq(fruits, oldFruits)); // true
console.log(arrEq(fruits, newFruits)); // false
console.log(arrEq(fruits, moreFruits)); // false

function arrEq(arr1, arr2) {
  let arrLength;
  if ((arrLength = arr1.length) != arr2.length) return false;
  for (let i = 0; i < arrLength; i++) if (arr1[i] !== arr2[i]) return false;
  return true;
}

And, for Pete’s sake (if you have a friend called ‘Pete’) - don’t use the above code. Who names variables arr1 and arr2 - that is so lame.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things