To find common elements in two arrays in JavaScript, we simply need to make use of the JavaScript Array filter() and includes() methods. Here is the code to get this done.

var commonElementsArray = firstArray.filter(element => secondArray.includes(element));

Let’s add to this code and show an example to show how easy it is to find common elements in two arrays using JavaScript.


Let’s show the above code above being used on a couple of simple arrays of numbers.

var firstArray = [1,2,3,4,5];
var secondArray = [1,3,5];

var commonElementsArray = firstArray.filter(element => secondArray.includes(element));

console.log(commonElementsArray);

#Output
[1, 3, 5]

You can see the code above will create a new array for us via the filter() method. We can wrap this code in a function to make it really easy to reuse it to find common elements in two arrays.

We will simply call our function commonArrayElements(), which will take two parameters, the two arrays we want to look at. It will then return a single array with all of the common elements of both arrays.

Here is our function:

function commonArrayElements(array1,array2){
  return array1.filter(element => array2.includes(element));
};

Now let’s show some examples of this function in action.

function commonArrayElements(array1,array2){
  return array1.filter(element => array2.includes(element));
};

var array1 = [0,1,2,3,4,5,6,7,8,9];
var array2 = ['a','b','c','d','e','f'];
var array3 = [1,'a',-1,'b',-2,'e',false,"4","hello","Hello"];
var array4 = [-2,-4,-6,-8];
var array5 = ["hello",4,false,"hello"];

console.log(commonArrayElements(array1,array2));
console.log(commonArrayElements(array1,array3));
console.log(commonArrayElements(array2,array3));
console.log(commonArrayElements(array3,array4));
console.log(commonArrayElements(array3,array5));

#Output
[]
[1]
['a', 'b', 'e']
[-2]
[false, 'hello']

Check out how to use the filter() method in a similar way to find the number of even numbers in an array.

Hopefully this article has been useful for you to learn how to use JavaScript to find common elements in two arrays in JavaScript.

Categorized in:

JavaScript,

Last Update: March 11, 2024