javascript

JavaScript Check if Two Arrays Are Equal


In JavaScript to Check if two Arrays Are Equal the most simple approach is using a basic for loop with a counter. below is a simple example:

function checkArraysAreEqual(arrayA, arrayB) {
  if (!Array.isArray(arrayA) || !Array.isArray(arrayB)) {
    return false;
  } else if (arrayA === arrayB) {
    return true;
  } else if (arrayA.length !== arrayB.length) {
    return false;
  } else {
    for (let x = 0; x < arrayA.length; ++x) {
      if (arrayA[x] !== arrayB[x]) return false;
    }
    return true;
  }
}
const vegetableNamesA = ["potato", "tomato", "onion", "ladyfinger"];
const vegetableNamesB = ["tomato", "onion", "ladyfinger", "potato"];

console.log(
  checkArraysAreEqual(vegetableNamesA.sort(), vegetableNamesB.sort())
);

In the code snippet above we sort our arrays before we test them for equality. The above code returns True in the console.


Share on social media

//