Struggling to find matching elements in two JavaScript arrays? This guide teaches you with different approaches to get the common elements from two arrays.
JavaScript Methods Used:
includes()
indexOf()
filter()
JavaScript loop used:
For Loop
Get Common Items From Two Arrays.
Approach 1: Combining filter() and include() method.
This approach uses the filter() and includes() methods. The filter() method creates a new array containing only the elements from the original array that pass a test implemented by a provided function.
Within this function, we check for common items between arrays using the includes() method. The function iterates through each element in the first array and checks if it's present in any element of the second array. The includes() method returns true, if a match is found, otherwise, it returns false. And when the includes() method returns true, that element is stored in a new array created by the filter method.
JavaScript
let fruits_array_1 = ["mango", "banana", "apple", "pineapple"];
let fruits_array_2 = ["mango", "guava", "banana", "orange"];
let common_items = fruits_array_1.filter(function(l,i){return fruits_array_2.includes(l) === true});
// Output:
// document.write(common_items);
// mango,banana
Here, You can also use the indexOf() method instead of the include() method.
indexOf() method returns -1 if no given array item is found.
JavaScript
let fruits_array_1 = ["mango", "banana", "apple", "pineapple"];
let fruits_array_2 = ["mango", "guava", "banana", "orange"];
let common_items = fruits_array_1.filter(function(l,i){return fruits_array_2.indexOf(l) !== -1});
// Output:
// document.write(common_items);
// mango,banana
Appraoch 2: Using for loop.
In this approach we use two for loops, one for each array. For each iteration of the first loop, the second loop (nested within the first) iterates through all elements of the second array. Within the inner loop, we compare each element of the second array to the current element of the first array. If a match is found, the element is stored in a third array.
JavaScript
let fruits_array_1 = ["mango", "banana", "apple", "pineapple"];
let fruits_array_2 = ["mango", "guava", "banana", "orange"];
let common_array_items = [];
for (let i = 0; i < fruits_array_1.length; i++) {
const element = fruits_array_1[i];
for (let k = 0; k < fruits_array_2.length; k++) {
const element2 = fruits_array_2[k];
// You can use includes() method.
// if(element.includes(element2)){
// common_array_items.push(element);
// }
// OR
// You can use indexOf() method.
// if(element.indexOf(element2) !== -1){
// common_array_items.push(element);
// }
// OR
if (element === element2) {
common_array_items.push(element);
}
}
}
// Output:
document.write(common_array_items);
// mango,banana
So that's how you can get the comment items from two arrays in JavaScript. If you have any query or suggestion feel free to write in the comment section.
Share your thoughts.