Find common items from two Arrays in JavaScript
In this tutorial, you will learn how to find common items from two arrays in JavaScript.
How to find if two arrays contain any common item in Javascript, find common elements only between 2 arrays, Get common elements in two arrays, Find common elements in a list of arrays, Comparison of Two arrays Using JavaScript, Get common elements from two Arrays.
Checkout more articles on 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
- First, initialize a new empty array.
- Now, iterate all the items in one of them array using for loop.
- In this for loop, iterate all the items of the other array.
- If the item is present, then add to the new array.
- Otherwise continue with the new item.
By following the above steps, we will create a function that returns the common items from two arrays.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | 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] |
Method 2: Using forEach
Let’s use the forEach
method to get the common items from two arrays.
1 2 3 4 5 6 7 8 | const array1 = [1, 4, 5, 6, 8]; const array2 = [1, 2, 3, 8, 9]; const uniqueItems = []; array1.forEach(num1 => { array2.forEach(num2 => num1 === num2 && uniqueItems.push(num1)); }); console.log(uniqueItems); // Output: [1, 8] |
That’s it for today.
Thank you for reading. Happy Coding!