[英]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
:我可以通过结合使用
filter
和indexOf
来实现:
[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 方法之一,所以我非常感谢一些建议。
ES6, a propoosal with Array#includes<\/code><\/a>
ES6,一个带有
Array#includes<\/code><\/a>的提案
<\/blockquote>
Just a smarter approach with using a single array which contains all arrays.使用包含所有数组的单个数组只是一种更智能的方法。
var aa = ['a','b','c','d'], bb = ['b','d','f','h'], result = [aa, bb].reduce((a, b) => a.filter(c => b.includes(c))); console.log(result);<\/code><\/pre>
"
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>
![](/img/trans.png)
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>
![](/img/trans.png)
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.