How to Get Array Intersection in JavaScript

Mehvish Ashiq Feb 02, 2024
  1. Using the _.intersection() Method to Find Array Intersection in JavaScript
  2. Using the filter() With indexOf() & includes() Methods to Find Array Intersection in JavaScript
  3. Using the Set’s has() Method to Find Array Intersection in JavaScript
  4. Using jQuery to Find Array Intersection in JavaScript
How to Get Array Intersection in JavaScript

We are focusing on the JavaScript array intersection in this tutorial. Finding an intersection between two arrays means looking for the common elements in arrayA and arrayB.

To do this via programming, we use _.intersection() function, filter() and indexOf() methods together, filter() and includes() at once, and has() method of a set with includes() function.

We can also accomplish this goal by using jQuery. Let’s step into it one by one.

Using the _.intersection() Method to Find Array Intersection in JavaScript

The _.intersection() is a function from JavaScript’s Underscore library that returns the array of common values from the passed arrays. The plus point of using this function is passing more than two arrays.

You can dive into the detail of the Underscore library here.

Make sure to include the Underscore library within the <head> tag.

Example Code:

let results = _.intersection([2, 3, 4, 5, 6], [3, 4, 6, 2]);
console.log(results);

Output:

[2, 3, 4, 6]

Suppose if we have string arrays, the _.intersection() still works the same as it was working for numbers’ array and looking for common elements among arrays.

See the example code given below.

let results = _.intersection(
    ['mehvish', 'ashiq', 'martell', 'daniel'],
    ['daniel', 'raza', 'christopher'], ['ashiq', 'daniel', 'moultrie']);
console.log(results);

Output:

["daniel"]

Do you think _.intersection() will generate the error if we pass the arrays having null, "" (empty string), undefined values? No, it does not.

It will still try to find the same elements in all the provided arrays. Have a look at the following code to practice.

let results = _.intersection(['null', '', 'undefined', 3], [3, 'null', '']);
console.log(results);

Output:

["null", "", 3]

Using the filter() With indexOf() & includes() Methods to Find Array Intersection in JavaScript

The filter() function creates a brand new array with the elements that pass the assessment implemented by the given function.

The indexOf() method gives us the position of the first occurrence of the a value and returns -1 if not found.

On the other side, the includes() method determines whether the array has a particular value amidst its entries. It returns true and false depending on the input.

Example Code:

let arrayA = [2, 3, 5, 4, 7, 9];
let arrayB = [2, 9, 4, 7];
const filteredArray = arrayA.filter(value => arrayB.includes(value));
console.log(filteredArray);

Output:

[2, 4, 7, 9]

Example Code:

let arrayA = [2, 3, 5, 4, 7, 9];
let arrayB = [2, 9, 4, 7];
const filteredArray = arrayA.filter(value => arrayB.indexOf(value) !== -1);
console.log(filteredArray);

Output:

[2, 4, 7, 9]

Using the Set’s has() Method to Find Array Intersection in JavaScript

The includes() method looks for every element in the array, which means its time complexity is O(n).

Here, the has() method comes into the picture and returns the output in a constant time, also known as O(1).

We must convert our arrays to sets and then write a for loop to use the has() function to follow this technique.

Example Code:

let arrayA = [2, 3, 5, 4, 7, 9];
let arrayB = [2, 9, 4, 7];
// converting into Set
let setA = new Set(arrayA);
let setB = new Set(arrayB);
for (let i of setB) {
  if (setA.has(i)) {
    console.log(i);
  }
}

Output:

2
9
4
7

What if we want to have the common values in a separate array? We can use the push() method to insert the commonValues array values.

Practice with the following code to learn; you can find more information about the push() method here.

let arrayA = [2, 3, 5, 4, 7, 9];
let arrayB = [2, 9, 4, 7];
// converting into Set
let setA = new Set(arrayA);
let setB = new Set(arrayB);
let commonValues = [];

for (let i of setB) {
  if (setA.has(i)) {
    commonValues.push(i);
  }
}
console.log(commonValues);

Output:

[2, 9, 4, 7]

Using jQuery to Find Array Intersection in JavaScript

If you love to work with jQuery, the following solution is good. The grep() function finds the array elements that fulfills the filter() function.

Remember, the original array is not affected by this function. The inArray() is just like the JavaScript indexOf() method.

It also searches for the value/element in the array and returns its position. The inArray() returns -1 if value not found in the array.

Example Code:

let arrayA = [2, 3, 5, 4, 7, 9], arrayB = [2, 9, 4, 7];

$.arrayIntersect = function(arrA, arrB) {
  return $.grep(arrA, function(i) {
    return $.inArray(i, arrB) > -1;
  });
};
console.log($.arrayIntersect(arrayA, arrayB));

Output:

[2, 4, 7, 9]
Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

Related Article - JavaScript Array