简体   繁体   English

Array.prototype.reduce 的数组交集(集合论)

[英]Array intersection (set-theoretic) with Array.prototype.reduce

I have two arrays [a,b,c,d] and [b,d,f,h] .我有两个数组[a,b,c,d][b,d,f,h]

I want to get an array back with the common elements [b,d] .我想用公共元素[b,d]取回一个数组。

I can achieve that with a combination of filter and indexOf :我可以通过结合使用filterindexOf来实现:

[a,b,c,d].filter(el => [b,d,f,h].indexOf(el) !== -1)

but I was wondering if and how I can do the same with reduce .但我想知道是否以及如何对reduce做同样的事情。

I admit that, despite looking at many examples, reduce still is to me one of the most obscure JS methods, so I'd really appreciate some advice.我承认,尽管看了很多例子, reduce对我来说仍然是最晦涩的 JS 方法之一,所以我非常感谢一些建议。

Reduce is designed to return a single value from a list of items. Reduce 旨在从项目列表中返回单个值。 So filter makes much more sense here.所以过滤器在这里更有意义。

A good use for reduce would be to return the total number of common elements. reduce 的一个很好的用途是返回公共元素的总数。 Check it out here: https://jsfiddle.net/c69vgzL4/在这里查看: https ://jsfiddle.net/c69vgzL4/

var a = ['a','b','c','d']
var b = ['b','d','f','h']

var number_of_common = b.reduce(function(prev, next) {
    return prev + (a.indexOf(next) + 1 ? 1 : 0)
}, 0)

$('body').html(number_of_common)

Not only two arrays but for an intersection of n arrays... Let's invent Array.prototype.intersect()<\/code>不仅是两个数组,还有 n 个数组的交集……让我们发明Array.prototype.intersect()<\/code>

 Array.prototype.intersect = function(...a) { return [this,...a].reduce((p,c) => p.filter(e => c.includes(e))); } var arrs = [[0,2,4,6,8],[4,5,6,7],[4,6]], arr = [0,1,2,3,4,5,6,7,8,9]; console.log(JSON.stringify(arr.intersect(...arrs))); \/\/ or just do console.log(JSON.stringify(["a","b","c","d"].intersect(["b","d","f","h"])));<\/code><\/pre>

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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