简体   繁体   English

根据javascript中的匹配条件从数组数组中查找匹配项

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

Given I have an array of arrays like the following: 鉴于我有一个数组,如下所示:

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

The condition is the array have to matches with 2 matches or more with each other, then it will store into the new array for the result of it. 条件是数组必须相互匹配2个或更多个匹配项,然后它将结果存储到新数组中。

I am using the following javascript method, and the method will compare for every single one of arrays within an array. 我正在使用以下javascript方法,该方法将针对数组中的每个数组进行比较。

What I am trying to do is to make the javascript method to not loop every single one of arrays within an array to look for the matches, but it is will be based on the condition stated above (2 matches or more) 我正在尝试做的是使javascript方法不循环数组中的每个数组来查找匹配项,但这将基于上述条件(2个匹配项或更多)

Javascript method: 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; }, []) ) 

Result of the array above will be empty, what I expect it to based on the condition stated above (2 matches or more) is: 上面的数组的结果将为空,根据上述条件(至少2个匹配项),我希望它是:

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

Your answer will be much appreciated! 您的回答将不胜感激!

Thanks 谢谢

For on O(N) solution (your current .every inside .reduce is O(N^2) ), you can use reduce to create an object indexed by strings, whose values are the number of occurrences of that string. 有关O(N)解决方案(当前的.every里面.reduceO(N^2)可以使用reduce创建的字符串,其值是字符串的出现次数索引的对象。 Then, .filter over the object's keys to get those which have at least a count of two: 然后,对对象的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); 

Note that because you had two " 001" strings in the input, they're included in the output as well. 请注意,由于输入中包含两个" 001"字符串,因此它们也包含在输出中。

For an ES5 version, I ran the above through Babel and got: 对于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