Find common values from two Arrays in JavaScript
📅July 2, 2021
In this tutorial, you will learn how to find common values from two arrays in JavaScript.
- How to compare two dates in JavaScript
- JavaScript array methods Push, Pop, Shift and Unshift
- JavaScript Spread Operator
- How to remove duplicates from an Array in JavaScript
- How to get the current URL using JavaScript
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.
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!