Skip to content

JavaScript Array intersection | Simples example code

  • by

The intersection means get elements of arrays that are common. Simply use filter() and includes() method to do JavaScript Array intersection.

Example of JavaScript Array intersection

Use a combination of Array.prototype.filter and Array.prototype.includes:

 const filteredArray = array1.filter(value => array2.includes(value));

Let’s see a simple HTML example of it:-

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript">
        //test
        array1 = [1,2,3]
        array2 = [2,3,4,5,6]

        var filteredArray = array1.filter(function(n) {
            return array2.indexOf(n) !== -1;
        });

        alert(filteredArray)

    </script>
</head>
<body>

</body>
</html>

Output:

JavaScript Array intersection

Source: Stackoverflow.com

Do comment if you have other examples or doubts or suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading