admin管理员组

文章数量:1421978

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 0
Add a ment  | 

1 Answer 1

Reset to default 5

Use 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);

本文标签: javascriptFind the index of a sub array that contains a numberStack Overflow