【问题标题】:Using reduce, from an array of objects, create a set of elements inside the objects' array attributes使用reduce,从对象数组中,在对象的数组属性中创建一组元素
【发布时间】: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


【解决方案1】:

您可以在累加器中concatbar 属性,并使用.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);

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2023-02-09
      • 1970-01-01
      • 2021-03-30
      • 2019-09-09
      • 1970-01-01
      相关资源
      最近更新 更多