[英]Using reduce, from an array of objects, create a set of elements inside the objects' array attributes
Given the following array:给定以下数组:
foos = [
{
id: 0,
bar: ['a','b','c']
},
{
id: 1,
bar: ['a','b','d']
},
{
id: 2,
bar: ['a','c']
},
]
Using reduce
, how can I achieve the following?:使用
reduce
,我怎样才能实现以下目标?:
bars == ['a','b','c','d']
I've tried:我试过了:
foo.reduce((bars, foo) => bars.add(foo.bar), new Set())
But it results in a set of objects:但它会产生一组对象:
Set { {0: 'a', 1: 'b', 2: 'c'}, {0: 'a', 1: 'b', 2: 'd'}{0: 'a', 1: 'c'}}
And:和:
foos.reduce((bars, foo) => foo.bar.forEach(bar => bars.add(bar)), new Set())
But the forEach
has no access to the bars
set.但是
forEach
无法访问bars
集。
Instead of creating a Set inside your reduce .而不是在您的reduce中创建一个Set 。 You could just reduce all
bar
arrays into a single one and pass that to your Set constructor.您可以将所有
bar
数组减少为一个,并将其传递给您的 Set 构造函数。
const foos = [ { id: 0, bar: ['a','b','c'] }, { id: 1, bar: ['a','b','d'] }, { id: 2, bar: ['a','c'] }, ]; const bars = new Set(foos.reduce((all, foo) => [...all, ...foo.bar], [])); console.log(...bars);
const foos = [ { id: 0, bar: ['a','b','c'] }, { id: 1, bar: ['a','b','d'] }, { id: 2, bar: ['a','c'] }, ]; const bars = new Set(foos.flatMap(foo => foo.bar)); console.log(...bars);
You can concat
the bar
property in the accumulator, and use .filter
method to make the values unique:您可以
concat
该bar
在累加器财产,并使用.filter
方法做出独特的价值:
const foos = [{ id: 0, bar: ['a', 'b', 'c'] }, { id: 1, bar: ['a', 'b', 'd'] }, { id: 2, bar: ['a', 'c'] }, ]; const bars = foos .reduce((acc, itm) => acc.concat(itm.bar), []) .filter((i, x, s) => s.indexOf(i) === x); console.log(...bars);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.