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 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);
本文标签: javascriptFind the index of a sub array that contains a numberStack Overflow
版权声明:本文标题:javascript - Find the index of a sub array that contains a number - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745340628a2654245.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论