admin管理员组文章数量:1426464
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?:
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.
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?:
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.
- Use map inside reduce, you are pushing bar array into set, that is pushing whole bar object into set – Awais Commented Oct 20, 2021 at 12:07
-
You need to loop through
foo.bar
and add them individually tobars.add()
. And return thebars
set from thereduce
– adiga Commented Oct 20, 2021 at 12:12 -
1
Or to shorten it:
new Set( foos.flatMap(f => f.bar) )
– adiga Commented Oct 20, 2021 at 12:13
2 Answers
Reset to default 5Instead of creating a Set inside your reduce. You could just reduce all bar
arrays into a single one and pass that to your Set constructor.
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);
With flatMap:
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:
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);
本文标签:
版权声明:本文标题:javascript - Using reduce, from an array of objects, create a set of elements inside the objects' array attributes - Sta 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745476230a2659976.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论