• Post category:JavaScript
  • Reading time:3 mins read

In this tutorial, you will learn how to find common values from two arrays in JavaScript.

There are many ways to find common items from two arrays. But we explain here one of them using for loop.

Follow the steps below to find common items from two arrays

  1. First, initialize a new empty array.
  2. Now, iterate all the items in one of them array using for loop.
  3. In this for loop, iterate all the items of the other array.
  4. If the item is present, then add to the new array.
  5. Otherwise continue with the new item.

By following the above steps, we will create a function that returns the common items from two arrays.

function getCommonItems(array1, array2) {
  var common = []; // Initialize array to contain common items
  
  for (var i = 0; i < array1.length; i++) {
    for (var j = 0; j < array2.length; j++) {
      if (array1[i] == array2[j]) { // If item is present in both arrays
        common.push(array1[i]); // Push to common array
      }
    }
  }

  return common; // Return the common items
}

var array1 = [1,4,5,6,8];
var array2 = [1,2,3,8,9];

// Get common items of array1, array2
var commonItemList= getCommonItems(array1, array2); 

console.log(commonItemList);

// Output: [1, 8]

That’s it for today.
Thank you for reading. Happy Coding!

Leave a Reply