If I have two arrays of strings in JavaScript, how do I extract the strings that both arrays have in common? For example, if I have one array ['Apple','Orange','Grape']
and another array ['Apple']
, how do I get the result Apple
?
Asked
Active
Viewed 451 times
-2
-
2Does this answer your question? [Simplest code for array intersection in javascript](https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript) – Martheen Oct 16 '20 at 02:17
1 Answers
0
This is a data structure problem. You can simply create an object for Array1, and then search for the keys in Object which are in Array2.
Array1 = ['Apple','Orange','Grape'];
Array2 = ['Apple','Lemon','Mango','Grape'];
array1 = ['Apple','Orange','Grape'];
array2 = ['Apple','Lemon','Mango','Grape'];
let obj = {};
for (let fruit of array1) {
obj[fruit] = 1;
}
let commonArray = [];
array2.forEach(fruit => {
if (obj[fruit] === 1) {
commonArray.push(fruit);
}
})
common array will contain Apple and Grape;

Vikram
- 714
- 1
- 5
- 10