简体   繁体   中英

Filtering multi-dimensional array based on another array elements

I have two arrays in the code below - which matches is the main one and the other played which serves it is purpose for elements to filter out in the main array:

var matches = [[1,4],[3,1],[5,2],[3,4],[4,5],[2,1]];
var played = [2,5];

I need to filter out elements in matches based on played array, which means if there is any 2 or 5 in, then remove it altogether. Also the played array can be any length, min is 1.

Expected output should be

[[1,4],[3,1],[3,4]];

So I have tried this piece of code, but it doesn't yield the result I want.

var result = matches.map(x => x.filter(e => played.indexOf(e) < 0))

So anyway to achieve this?

While filtering, check that .every one of the subarray elements are not included in [2, 5] :

 var matches = [[1,4],[3,1],[5,2],[3,4],[4,5],[2,1]]; var played = [2,5]; const result = matches.filter( subarr => played.every( num => !subarr.includes(num) ) ); console.log(result);

You could check with some and exclude the unwanted arrays.

 var matches = [[1, 4], [3, 1], [5, 2], [3, 4], [4, 5], [2, 1]], played = [2, 5], result = matches.filter(a => !a.some(v => played.includes(v))); console.log(result);

Another way would be to create a Set of played to avoid iterating it again and again:

 var matches = [[1,4],[3,1],[5,2],[3,4],[4,5],[2,1]]; var played = new Set([2,5]); var out = matches.filter(a => !a.some(num => played.has(num))); console.info(out)

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