【发布时间】:2018-09-29 19:05:27
【问题描述】:
我有一个这样的数组:
const fruits = [
{ fruit: 'apple', year: 2018 },
{ fruit: 'apple', year: 2018 },
{ fruit: 'banana', year: 2018 },
{ fruit: 'orange', year: 2018 },
{ fruit: 'apple', year: 2017 },
{ fruit: 'apple', year: 2016 }
];
现在我想减少这个数组,看看每年有多少水果,总数是多少。所以结果看起来像这样:
const result = [
{ year: 2018, apple: 2, banana: 1, orange: 1 total: 4 },
{ year: 2017, apple: 1, total: 1 },
{ year: 2016, apple: 1, total: 1 }
];
我尝试过使用 reduce,但我不知道如何根据年份对其进行分组。也许还有一个 lodash 助手?
【问题讨论】:
标签: javascript arrays ecmascript-6 reduce