Suppose I have a multi dimensional array in JavaScript:
var arr = [
['cat','23','5123'],
['dog','53','522'],
['bird','335','512'],
['horse','853','152'],
['monkey','13','5452']
];
And I want to get the index of the array in arr that contains horse in the first index (output should be 3).
I can do this in the following way:
var index_i_need;
for(var i in arr){
if(arr[i][0]==='horse') {
index_i_need = i;
break;
}
}
console.log(index_i_need); // 3
console.log(arr[index_i_need]); // ['horse','853','152']
But this isnt scaleable.
Id like to have some more direct method like indexOf(), for instance.
I know findIndex() takes a callback function but I havent been able to apply it correctly.
Any suggestions?
1 Answer 1
You can use a dynamic find function, findByAnimal, to use in findIndex
function findByAnimal(animal) {
return function(innerArr){
return innerArr[0] === animal
}
}
arr.findIndex( findByAnimal('horse') )
The way findIndex works is each item in arr is passed into the callback, the first "truthy" return value from callback will yield the index, or -1 if no items return truthy.
2 Comments
Explore related questions
See similar questions with these tags.
arr.findIndex(sa => sa[0] === "horse");