使用 reduce,从一个对象数组中,在对象的数组属性中创建一组元素

Using reduce, from an array of objects, create a set of elements inside the objects' array attributes

给定以下数组:

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 集合。

而不是创建 Set inside your reduce。您可以将所有 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);

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);

你可以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);