Open In App

Find the common elements of more than two JavaScript arrays ?

Given an HTML document having multiple arrays with some elements and the task is to get the common elements from arrays with the help of JavaScript. There are two approaches that are discussed below.

Approach 1: First get the arrays in 2-dimensional format then take the first array by shift() method and then filter out the elements from the first array which are common in all by using filter() method. The elements which are common in all arrays can be checked by every() method and if the element of first array matches with all elements then that element is returned.

Approach 2: First get the arrays in 2-dimensional format then use the reduce() method to get the access to all arrays one by one. variable(p) contains each array one by one and returns only elements of the array which are in variable(c) array by using filter() method. At the end variable(c) contains the array of common elements.


Article Tags :