与Array.prototype.reduce的数组交集(理论集) [英] Array intersection (set-theoretic) with Array.prototype.reduce
问题描述
我有两个数组 [a,b,c,d]
和 [b,d,f,h]
.
我想找回带有公共元素 [b,d]
的数组.
I want to get an array back with the common elements [b,d]
.
我可以结合使用 filter
和 indexOf
:
[a,b,c,d].filter(el => [b,d,f,h].indexOf(el) !== -1)
但是我想知道是否可以以及如何使用 reduce
进行同样的操作.
but I was wondering if and how I can do the same with reduce
.
我承认,尽管查看了许多示例,但 reduce
对我来说仍然是最晦涩的JS方法之一,因此,我非常感谢一些建议.
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.
推荐答案
ES6, a propoosal with Array#includes
includes()
方法确定数组是否包含某个元素,并返回true
或false
作为合适的.
在 aa
的每个循环中,如果在测试数组 bb
中找到该值,则reduce将元素添加到结果数组中.如果找不到,则返回先前的结果.
On every loop of aa
, reduce adds the element to the result array if the value is found in the test array bb
. If not found, the former result is returned.
var aa = ['a','b','c','d'],
bb = ['b','d','f','h'],
cc = aa.reduce((r, a) => bb.includes(a) && r.concat(a) || r, []);
console.log(cc);
使用包含所有数组的单个数组只是一种更聪明的方法.
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);
这篇关于与Array.prototype.reduce的数组交集(理论集)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!