Reputation: 45
If I have two arrays, in Javascript:
let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
let arr2 = ["Zebra", "Goat"];
How can I find the indexes of the larger array where there is a match and store them in another array so example output would be:
let indexes = [3,4]
Upvotes: 0
Views: 1361
Reputation: 6009
You can achieve the expected output using Array.map
and Array.findIndex
let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
let arr2 = ["Zebra", "Goat"];
const findIndexes = (param1, param2) => {
let arr1 = [...param1];
let arr2 = [...param2];
//swap the arrays if the no.of array elements
//in the second array are greater than first
if(arr1.length < arr2.length) {
[arr1, arr2] = [arr2, arr1];
}
//Loop through all the items of the smaller array
//check if the element is present in the bigger array
return arr2.map(a2 => arr1.findIndex(a1 => a1 === a2));
}
console.log(findIndexes(arr1, arr2));
//here for "test", we'll get index as -1, because
//if the matching element is not found, findIndex will
//return -1
let arr3 = ["Cat", "Goose", "test"];
console.log(findIndexes(arr3, arr1));
If you wish to get the indexes of the elements that are found and wish to filter out all the -1
s, below is the code for the same.
let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
let arr2 = ["Zebra", "Goat"];
const findIndexes = (param1, param2) => {
let arr1 = [...param1];
let arr2 = [...param2];
if(arr1.length < arr2.length) {
[arr1, arr2] = [arr2, arr1];
}
return arr2.map(a2 => arr1.findIndex(a1 => a1 === a2)).filter(ele => ele !== -1);
}
console.log(findIndexes(arr1, arr2));
let arr3 = ["Cat", "Goose", "test"];
console.log(findIndexes(arr3, arr1));
Upvotes: 1
Reputation: 4802
You could do it by mapping over your search-teams (arr2
) and then using the findIndex
Method on the source-array (arr1
) like this:
let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
let arr2 = ["Zebra", "Goat"];
const result = arr2.map(searchTerm => arr1.findIndex((compareTerm) => compareTerm === searchTerm));
console.log(result);
Upvotes: 1
Reputation: 156
let arr1 = ["Dog", "Cat", "Monkey", "Zebra", "Goat", "Goose"];
let arr2 = ["Zebra", "Goat"];
let indexes = []
arr1.forEach((item, index) => {
if(arr2.includes(item)){
indexes.push(index)
}
})
console.log(indexes)
Upvotes: 0