【问题标题】:Grouping with reduce in JS在 JS 中使用 reduce 进行分组
【发布时间】:2019-02-27 08:25:05
【问题描述】:

是否可以使用 array.reduce 方法按“国家”对它们进行分组? 任何建议表示赞赏。

const table = { 
  0: {
    firstName: 'Mark',
    lastName: 'Spencer',
    adress: {
      Country: 'England',
      Town:    'London',
      Street: 'Old street',
      Postcode: 'W2 1RB'
    }
  },
  1: {
    firstName: 'Franz',
    lastName: 'Muller',
    adress: {
      Country: 'Germany',
      Town: 'Berlin'
      Street: 'Wilhelmstrasse',
      Postcode: '10115 - 14199'
    }
  },
  2: {
    firstName: 'William',
    lastName: 'Davies',
    adress: {
      Country: 'England',
      Town:    'Liverpool'
      Street: 'New Street',
      Postcode: 'l1 0au'
    }

我怎样才能仅使用这种方法正确地对它们进行排序?

【问题讨论】:

  • 请更具体。你想对它进行分组还是排序?期望的输出是什么?为什么“仅此方法”? Array.prototype.reduce 不能应用于对象。
  • 您好,感谢您的提问。所需的输出是使用 array.reduce 按国家/地区对它们进行分组,这只是为了在更复杂的数组上练习 array.reduce。

标签: javascript arrays reduce


【解决方案1】:

您可以使用Object.values 将对象的值作为数组获取。你桌子的钥匙似乎没有任何意义;它们只是索引。这是您要分组的值:使用Object.values 可以清楚地说明这一点。

一旦你有了一个数组,你就可以使用Array.prototype.reduce。我将groupBy 包装在一个内部使用reduce 的可重用函数中。

const table = { 0: { firstName: 'Mark', lastName: 'Spencer', address: { Country: 'England', Town: 'London', Street: 'Old street', Postcode: 'W2 1RB' } }, 1: { firstName: 'Franz', lastName: 'Muller', address: { Country: 'Germany', Town: 'Berlin', Street: 'Wilhelmstrasse', Postcode: '10115 - 14199' } }, 2: { firstName: 'William', lastName: 'Davies', address: { Country: 'England', Town: 'Liverpool', Street: 'New Street', Postcode: 'l1 0au' } } };

const groupBy = (getId, array) => 
  array.reduce(
    (groups, x) => {
      const k = getId(x);
      if (!groups[k]) groups[k] = [];
      groups[k].push(x);
      return groups;
    },
    {}
  );
  
  
console.log(
  groupBy(
    person => person.address.Country,
    Object.values(table)
  )
)
    

【讨论】:

    【解决方案2】:

    您可以将带有 Object.assign 的索引等键的对象转换为数组,然后对其进行归约。

    var data = { 0: { firstName: 'Mark', lastName: 'Spencer', address: { Country: 'England', Town: 'London', Street: 'Old street', Postcode: 'W2 1RB' } }, 1: { firstName: 'Franz', lastName: 'Muller', address: { Country: 'Germany', Town: 'Berlin', Street: 'Wilhelmstrasse', Postcode: '10115 - 14199' } }, 2: { firstName: 'William', lastName: 'Davies', address: { Country: 'England', Town: 'Liverpool', Street: 'New Street', Postcode: 'l1 0au' } } },
        grouped = Object
            .assign([], data)
            .reduce((r, o) => {
                var key = o.address.Country;
                (r[key] = r[key] || []).push(o);
                return r;
            }, Object.create(null));
        
    console.log(grouped);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      猜你喜欢
      • 2013-03-12
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2022-12-06
      • 2014-04-09
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多