使用JavaScript中的给定字符串值获取多维数组的索引 [英] Get the index of a multidimensional array with the value of a given string in javascript
本文介绍了使用JavaScript中的给定字符串值获取多维数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数组,
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
我想获取 data [0] $ c $值
Mary
的数组的c>。
因此,在我的示例中,我将获得的值是不存在
。
And I want to get the data[0]
of the array that have value of "Mary"
.
So in my example, value that I will get is "absent"
.
我还希望获得值为 Josh
的数组arr2的索引。
因此,在第二个数组中,我得到的值为0。
I want also to get the index of the array arr2 that have value of "Josh"
.
So in my second array, value that I will get is 0.
如果可以使用下划线js,我们可以使用它。
我尝试使用 _。contains()
,但失败了。
这些数组也用于淘汰赛js。
If possible to use underscore js, we can use it.
I tried to use _.contains()
but failed.
Also these array is used in knockout js.
推荐答案
另一种完成此工作的方法如下:
One other way of doing this job could be as follows;
var a1 = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]],
a2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]],["S",["Sally","Sam","Sammy Davis"]]],
getStatus = (a,n) => a.find(e => e[1].indexOf(n) !== -1)[0],
getIndex = (a,n) => a.findIndex(e => e[1].indexOf(n) !== -1);
console.log(getStatus(a1,"Mary"));
console.log(getIndex(a2,"Sammy Davis"));
这篇关于使用JavaScript中的给定字符串值获取多维数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文