Checking If One Array Contains an Item from Another Array in...

by Michael Szul on

No ads, no tracking, and no data collection. Enjoy this article? Buy us a ☕.

You know what old school is? Old school is putting a for loop inside of a for loop to check to see if two arrays contain the same element.

What do I mean?

Imagine you have this:

const a1 = [1, 2, 3, 4, 5];
      const a2 = [5, 6, 7, 8, 9];
      

This is a simply array example, but you could also assume that they are arrays of objects, and you want to check properties on those objects.

With the arrays above, how would you check to see if a2 contains a value that is in a1?

Okay, now how would you do it without two for loops?

This is where JavaScript's some() method comes into play. This allows you to test if "some" elements (by not necessarily all) in an array pass a certain test. So if we're trying to check elements in both arrays, what would that look like?

const b = a1.some((val) => a2.indexOf(val) !== -1);
      

That's pretty concise, huh?

In the example about, we use some(), which performs a test on each element in the a1 array. During that loop--which we conveniently have in a single line arrow function--we then check that the second array (a2) contains the value (val) from the first array by using the array object's indexOf() method. If the index value is not -1, then we know the array contains the value, and this line will return true. Since we're using some(), if at least one test is true, then "some" of the items are in each array, which then means that b is true.