简体   繁体   中英

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.

I am using the following javascript method, and the method will compare for every single one of arrays within an array.

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 method:

 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:

["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. Then, .filter over the object's keys to get those which have at least a count of two:

 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.

For an ES5 version, I ran the above through Babel and got:

 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM