OneBite.Dev - Coding blog in a bite size

find the common elements in two arrays in Javascript

Code snippet on how to find the common elements in two arrays in Javascript

  const array1 = [45, 18, 22, 34];
  const array2 = [22, 11, 45, 18, 67];
  
  const commonElements = array1.filter(element => array2.includes(element));
  
  console.log(commonElements); // [45, 18, 22]

This code finds the common elements in two arrays. The first two lines store two arrays in the constant variables named array1 and array2. The third line creates a new constant variable called commonElements that is initialized with a filter method on the array1. The filter method looks for every element of array1 one by one and passes it to the callback function in the filter option that has to be a boolean expression. The callback function checks if the element is included in array2. If it is included it gets added to the commonElements array. The fourth and the last line logs the commonElements variable to the console. The output of the code will be an array with the common elements such as [45, 18, 22].

javascript