var array = [[2,3,4],[4,5,6],[2,3,9]];
var number = 9;
If I have this nested array and this variable how do I return the index where the sub-array with the number is. So the final result should be 2 or.
So far I have:
var indexOfRemainingArray = array.filter(function(item,i) {
if(item != number) {
return i;
}
});
I would like to know how to use map or filter functions for this.
var array = [[2,3,4],[4,5,6],[2,3,9]];
var number = 9;
If I have this nested array and this variable how do I return the index where the sub-array with the number is. So the final result should be 2 or.
So far I have:
var indexOfRemainingArray = array.filter(function(item,i) {
if(item != number) {
return i;
}
});
I would like to know how to use map or filter functions for this.
Share Improve this question edited Jun 14, 2017 at 19:52 Ori Drori 194k32 gold badges238 silver badges229 bronze badges asked Jun 14, 2017 at 19:43 Pablo.KPablo.K 1,1512 gold badges10 silver badges15 bronze badges 01 Answer
Reset to default 5Use Array#findIndex
to find the index, and use Array#indexOf
in the callback to check if the sub array contains the number at least once.
var array = [[2,3,4],[4,5,6],[2,3,9]];
var number = 9;
var indexOfRemainingArray = array.findIndex(function(sub) {
return sub.indexOf(number) !== -1;
});
console.log(indexOfRemainingArray);
And if you need both indexes, you can assign the result of the inner indexOf
to a variable:
var array = [[2,3,4],[4,5,9],[2,3,1]];
var number = 9;
var innerIndex;
var indexOfRemainingArray = array.findIndex(function(sub) {
innerIndex = sub.indexOf(number);
return innerIndex !== -1;
});
console.log(indexOfRemainingArray, innerIndex);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745340628a4623310.html
评论列表(0条)