Skip to main content Accessibility Feedback

arrayIntersect.js

Get the intersecting values between two arrays.

Source Code

Example

let wizards = ['Merlin', 'Gandalf', 'Ursula'];
let magicalFolk = ['Gandalf', 'Radagast', 'Ursula', 'Morgana'];

// returns ['Gandalf', 'Ursula']
let overlap = arrayIntersect(wizards, magicalFolk);

The helper function

/**
 * Get the intersecting values between two arrays
 * (c) Chris Ferdinandi, MIT License, https://gomakethings.com
 * @param  {Array} arr1 The first array
 * @param  {Array} arr2 The second array
 * @return {Array}      The array of overlapping values
 */
function arrayIntersect (arr1, arr2) {
	return arr1.filter(function (item) {
		return arr2.includes(item);
	});
}

How it works

First, let’s create an arrayIntersect() function. We’ll accept two arrays, arr1 and arr2, as arguments.

/**
 * Get the intersecting values between two arrays
 * @param  {Array} arr1 The first array
 * @param  {Array} arr2 The second array
 * @return {Array}      The array of overlapping values
 */
function arrayIntersect (arr1, arr2) {
    // ...
}

Next, let’s use the Array.filter() method to create a new array containing just our overlapping values.

We’ll run it on the first array, arr1.

/**
 * Get the intersecting values between two arrays
 * @param  {Array} arr1 The first array
 * @param  {Array} arr2 The second array
 * @return {Array}      The array of overlapping values
 */
function arrayIntersect (arr1, arr2) {
    return arr1.filter();
}

Inside the callback function, we’ll check if the current item is in the second array, arr2, using the Array.includes() method. If it does, we’ll include it in our new array.

/**
 * Get the intersecting values between two arrays
 * @param  {Array} arr1 The first array
 * @param  {Array} arr2 The second array
 * @return {Array}      The array of overlapping values
 */
function arrayIntersect (arr1, arr2) {
    return arr1.filter(function (item) {
        return arr2.includes(item);
    });
}