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: In the code…

The post JavaScript Check if Two Arrays Are Equal appeared first on CodeSource.io.


This content originally appeared on CodeSource.io and was authored by Deven

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.

The post JavaScript Check if Two Arrays Are Equal appeared first on CodeSource.io.


This content originally appeared on CodeSource.io and was authored by Deven


Print Share Comment Cite Upload Translate Updates
APA

Deven | Sciencx (2021-02-07T15:06:21+00:00) JavaScript Check if Two Arrays Are Equal. Retrieved from https://www.scien.cx/2021/02/07/javascript-check-if-two-arrays-are-equal/

MLA
" » JavaScript Check if Two Arrays Are Equal." Deven | Sciencx - Sunday February 7, 2021, https://www.scien.cx/2021/02/07/javascript-check-if-two-arrays-are-equal/
HARVARD
Deven | Sciencx Sunday February 7, 2021 » JavaScript Check if Two Arrays Are Equal., viewed ,<https://www.scien.cx/2021/02/07/javascript-check-if-two-arrays-are-equal/>
VANCOUVER
Deven | Sciencx - » JavaScript Check if Two Arrays Are Equal. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/02/07/javascript-check-if-two-arrays-are-equal/
CHICAGO
" » JavaScript Check if Two Arrays Are Equal." Deven | Sciencx - Accessed . https://www.scien.cx/2021/02/07/javascript-check-if-two-arrays-are-equal/
IEEE
" » JavaScript Check if Two Arrays Are Equal." Deven | Sciencx [Online]. Available: https://www.scien.cx/2021/02/07/javascript-check-if-two-arrays-are-equal/. [Accessed: ]
rf:citation
» JavaScript Check if Two Arrays Are Equal | Deven | Sciencx | https://www.scien.cx/2021/02/07/javascript-check-if-two-arrays-are-equal/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.