Categories
JavaScript Answers

How to Check If Two JavaScript Arrays Have the Same Values?

Spread the love

One way to check if 2 JavaScript arrays have the same items in them is to sort them and then convert them to a string.

This works if all the array items are primitive values.

For instance, we can 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');
}

We call sort on array1 and array2 .

Then we call join on both to join all the items in each array into one string separated by commas.

If they’re the same in string form, then 'same' is logged.

Use the Lodash isEmpty and xor Methods

The Lodash isEmpty method lets us check if an array is empty.

xor lets us create an array that has items that’s either in one array or the other.

Therefore, we can use it to check if 2 arrays are the same.

For instance, we can 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 (_.isEmpty(_.xor(array1, array2))) {
  console.log('same');
}

We call xor with array1 and array2 to returns an array with items that are only in array1 or array2 .

And we call isEmpty with the returned array to check if it’s empty.

Since it’s empty, there are no items from each array that is exclusive to only that array.

Therefore, 'same' is logged.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published. Required fields are marked *