簡體   English   中英

返回包含字符串的嵌套數組的最有效方法 (JavaScript)

[英]Most efficient way to return a nested array that includes a string (JavaScript)

我想知道是否有更有效的方法來訪問基於匹配值的嵌套數組,而不是使用“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; }, Object.create(null) ); console.log(cache['222']);

現代 ES2019 版本,使用 flatMap 和 Map:

 const a = [ ["aaa", "111", "!!!"], ["bbb", "222", "@@@"], ["ccc", "333", "###"], ["ddd", "444", "$$$"] ]; const m = new Map(a.flatMap(r=>r.map(i=>[i,r]))); console.log(m.get('222'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM