javascript - Find the index of a sub array that contains a number - Stack Overflow

var array = [[2,3,4],[4,5,6],[2,3,9]];var number = 9;If I have this nested array and this variable how

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745340628a4623310.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信