【发布时间】:2021-12-07 06:06:27
【问题描述】:
给定以下数组:
foos = [
{
id: 0,
bar: ['a','b','c']
},
{
id: 1,
bar: ['a','b','d']
},
{
id: 2,
bar: ['a','c']
},
]
使用reduce,如何实现以下功能?:
bars == ['a','b','c','d']
我试过了:
foo.reduce((bars, foo) => bars.add(foo.bar), new Set())
但它会产生一组对象:
Set { {0: 'a', 1: 'b', 2: 'c'}, {0: 'a', 1: 'b', 2: 'd'}{0: 'a', 1: 'c'}}
还有:
foos.reduce((bars, foo) => foo.bar.forEach(bar => bars.add(bar)), new Set())
但是forEach 无法访问bars 集合。
【问题讨论】:
-
在reduce中使用map,你将bar数组推入set,也就是将整个bar对象推入set
-
您需要循环访问
foo.bar并将它们单独添加到bars.add()。并从reduce中返回bars集 -
或者缩短它:
new Set( foos.flatMap(f => f.bar) )
标签: javascript set reduce