Categories
JavaScript Answers

How to check if two arrays have the same values with JavaScript?

Spread the love

To check if two arrays have the same values with JavaScript, we sort them before comparing them.

For instance, we write

const array1 = [
  10, 6, 19, 16, 14, 15, 2, 9, 5, 3, 4, 13, 8, 7, 1, 12, 18, 11, 20, 17,
];
const array2 = [
  12, 18, 20, 11, 19, 14, 6, 7, 8, 16, 9, 3, 1, 13, 5, 4, 15, 10, 2, 17,
];

if (array1.sort().join(",") === array2.sort().join(",")) {
  console.log("same members");
}

to call sort to sort the numbers in the arrays and then we call join to join the entries with commas to form a string.

Then we compare them with === to see if they’re the same.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.