我想知道是否有一种更有效的方法来基于匹配的值访问嵌套数组,而不是使用'forEach'或'for'循环。
这是我目前所拥有的:
var a = [
["aaa", "111", "!!!"],
["bbb", "222", "@@@"],
["ccc", "333", "###"],
["ddd", "444", "$$$"]
];
var b = "222";
var c;
a.forEach((aa) => {
if (aa.includes(b)) c = aa;
});
// Ideally c would return ["bbb", "222", "@@@"]
console.log(c);
谢谢
我假设您想找到第一个有针的阵列:
var a = [
["aaa", "111", "!!!"],
["bbb", "222", "@@@"],
["ccc", "333", "###"],
["ddd", "444", "$$$"]
];
function search(haystack, needle) {
return haystack.find( item => item.includes(needle) );
}
console.log(search(a,'222'));
如果数据是静态的,则可以创建一个缓存,并使用指针来获取数组。
var a = [
["aaa", "111", "!!!"],
["bbb", "222", "@@@"],
["ccc", "333", "###"],
["ddd", "444", "$$$"]
];
const cache = a.reduce( (out, row) =>{
for (const item of row) out[item] = row;
return out;
},{});
console.log(cache['222']);
尝试使用JS find内置函数。它将返回满足的第一个元素。
var a = [
["aaa", "111", "!!!"],
["bbb", "222", "@@@"],
["ccc", "333", "###"],
["ddd", "444", "$$$"]
];
var b = "222";
var c = a.find(item => item.includes(b));
console.log(c) // ["bbb", "222", "@@@"]