Efficient Array Intersection in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the concept of array intersection in JavaScript. The main objective of this lab is to help you understand how to find common elements between two arrays while removing any duplicate values. You will learn how to use the Set data structure and the Array.prototype.filter() method to achieve this functionality.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28148{{"`Efficient Array Intersection in JavaScript`"}} javascript/data_types -.-> lab-28148{{"`Efficient Array Intersection in JavaScript`"}} javascript/arith_ops -.-> lab-28148{{"`Efficient Array Intersection in JavaScript`"}} javascript/comp_ops -.-> lab-28148{{"`Efficient Array Intersection in JavaScript`"}} javascript/higher_funcs -.-> lab-28148{{"`Efficient Array Intersection in JavaScript`"}} javascript/spread_rest -.-> lab-28148{{"`Efficient Array Intersection in JavaScript`"}} end

Finding Array Intersection

To find the common elements between two arrays and remove duplicates, use the following code:

const intersection = (arr1, arr2) => {
  const set = new Set(arr2);
  return [...new Set(arr1)].filter((elem) => set.has(elem));
};

To use this code, open the Terminal/SSH and type node. Then call the intersection function with two arrays as arguments, like this:

intersection([1, 2, 3], [4, 3, 2]); // [2, 3]

This will return an array containing the elements that exist in both arrays, with duplicates removed.

Summary

Congratulations! You have completed the Array Intersection lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like