簡體   English   中英

根據javascript中的匹配條件從數組數組中查找匹配項

[英]Find matches from an array of arrays based on matches condition in javascript

鑒於我有一個數組,如下所示:

var array = [["001"," 003"],["002"," 001"],["001"," 002"],["002"," 001"], ["", "001"]]

條件是數組必須相互匹配2個或更多個匹配項,然后它將結果存儲到新數組中。

我正在使用以下javascript方法,該方法將針對數組中的每個數組進行比較。

我正在嘗試做的是使javascript方法不循環數組中的每個數組來查找匹配項,但這將基於上述條件(2個匹配項或更多)

JavaScript方法:

 var array = [["001"," 003"],["002"," 001"],["001"," 002"],["002"," 001"], ["", "001"]] console.log( array.shift().reduce(function(res, v) { if (res.indexOf(v) === -1 && array.every(function(a) { return a.indexOf(v) !== -1; })) res.push(v); return res; }, []) ) 

上面的數組的結果將為空,根據上述條件(至少2個匹配項),我希望它是:

["001", "002", " 001"]

您的回答將不勝感激!

謝謝

有關O(N)解決方案(當前的.every里面.reduceO(N^2)可以使用reduce創建的字符串,其值是字符串的出現次數索引的對象。 然后,對對象的keys進行.filter ,以獲得至少具有兩個數的keys

 const input = [["001"," 003"],["002"," 001"],["001"," 002"],["002"," 001"], ["", "001"]]; const obj = input.reduce((a, arr) => { arr.forEach((str) => { a[str] = (a[str] || 0) + 1; }); return a; }, {}); const output = Object.keys(obj) .filter(key => obj[key] >= 2) console.log(output); 

請注意,由於輸入中包含兩個" 001"字符串,因此它們也包含在輸出中。

對於ES5版本,我通過Babel運行了以上內容,並得到:

 var input = [["001", " 003"], ["002", " 001"], ["001", " 002"], ["002", " 001"], ["", "001"]]; var obj = input.reduce(function (a, arr) { arr.forEach(function (str) { a[str] = (a[str] || 0) + 1; }); return a; }, {}); var output = Object.keys(obj).filter(function (key) { return obj[key] >= 2; }); console.log(output); 

暫無
暫無

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

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