Reputation: 157
I currently have this problem where I cannot seem to find an answer specific to my problem.
Array1 = ["item1", "item2", "item3", "item4", "item5"]
Array2 = ["item2", "item5"]
I am looking to use the information from array2 to find within array1.
An example for this to output
Array1 has item2 and is at Array1[1]
If anyone can help me, thank you.
Upvotes: 0
Views: 62
Reputation: 8069
Array2.forEach((e) => {
const indexOfE = Array1.indexOf(e)
if (indexOfE > -1) {
console.log(`Array1 has ${e} and is at Array1[${indexOfE}]`)
}
})
You can have a look at forEach
, indexOf
, and template literals to help you understand this code.
Edit
Answering the question in the comments, if you want to check the elements in Array1 that contain elements of Array2 as substrings, then you can:
Array2.forEach((e) => {
Array1.forEach((f, i) => {
if (f.toLowerCase().includes(e)) {
console.log(`Array1 has ${e} and is at Array1[${i}]`)
}
})
})
Check String.prototype.includes
and this answer for details on finding substrings in another String.
Upvotes: 2
Reputation: 1866
You could Ramdajs to find intersection of two arrays as follows
const Array1 = ["item1", "item2", "item3", "item4", "item5"];
const Array2 = ["item2", "item5"];
const res = R.intersection(Array1, Array2);
console.log(res);
here is the code repel
The same could be achieved using lodash
const Array1 = ["item1", "item2", "item3", "item4", "item5"];
const Array2 = ["item2", "item5"];
const res = _.intersection(Array1, Array2)
console.log(res);
here is the jsfiddle for lodash.
or you could use the includes method of the array to do the same
const Array1 = ["item1", "item2", "item3", "item4", "item5"];
const Array2 = ["item2", "item5"];
const res = Array1.filter(curr=>Array2.includes(curr));
console.log(res);
Upvotes: 0
Reputation: 246
This is the code:
var Array1 = ["item1", "item2", "item3", "item4", "item5"];
var Array2 = ["item2", "item5"];
for (var i = 0; i <Array2.length; i++) {
if (Array1.indexOf(Array2[i])>-1) {
console.log("Array1 has "+Array2[i]+" and is at Array1["+Array1.indexOf(Array2[i]) +"]")
}
}
Upvotes: 0
Reputation: 1912
If you only want to know Array1 contains an element from Array2 then iterate over Array2 calling indexOf for each element:
Array2.map((el => {
if (Array1.indexOf(el) !== -1) {
console.log('Array 1 contains ' + el);
}
}));
Upvotes: 0