Check if two arrays are equal in Javascript

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.

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.

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.

comments powered by Disqus