Simplest Code for Array Intersection in Javascript

Simplest code for array intersection in JavaScript

As a JavaScript developer, you may often come across situations where you need to find the common elements between two or more arrays. This process is commonly known as “array intersection”. In this blog post, we will explore the simplest code to achieve array intersection in JavaScript.

Method 1: Using the filter() method

The filter() method allows us to create a new array with all elements that pass a certain condition. By using this method, we can easily find the common elements between two arrays.

const array1 = [1, 2, 3, 4, 5];
const array2 = [4, 5, 6, 7, 8];

const intersection = array1.filter(element => array2.includes(element));

console.log(intersection); // Output: [4, 5]

In the above code snippet, we have two arrays, array1 and array2. We use the filter() method on array1 and pass a callback function that checks if each element exists in array2 using the includes() method. The resulting array, intersection, will contain the common elements between the two arrays.

Method 2: Using the Set object

The Set object in JavaScript allows us to store unique values of any type. By converting our arrays into sets, we can easily find the common elements using the Set.prototype.intersection() method.

const array1 = [1, 2, 3, 4, 5];
const array2 = [4, 5, 6, 7, 8];

const set1 = new Set(array1);
const set2 = new Set(array2);

const intersection = new Set([...set1].filter(element => set2.has(element)));

console.log([...intersection]); // Output: [4, 5]

In the above code snippet, we first create two sets, set1 and set2, by passing our arrays as arguments to the Set constructor. We then use the filter() method on the spread operator of set1 to check if each element exists in set2 using the has() method. Finally, we convert the resulting set back to an array using the spread operator.

Both methods provide a simple and efficient way to find the common elements between arrays in JavaScript. You can choose the method that suits your specific requirements and coding style.

That’s it! You now have the simplest code for array intersection in JavaScript. Happy coding!


Posted

in

, ,

by

Tags:

Comments

Leave a Reply

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