JS(ES6):基于对象属性减少数组

时间:2018-04-19 10:07:21

标签: javascript arrays ecmascript-6 reduce

我有一个这样的数组:

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助手?

3 个答案:

答案 0 :(得分:3)

使用Object.valuesreduce

var output = Object.values(fruits.reduce( (a,c) => {
  a[c.year] = a[c.year] || { year : c.year };  
  a[c.year]["total"] = (a[c.year]["total"] || 0) + 1;
  a[c.year][c.fruit] = (a[c.year][c.fruit] || 0) + 1;
  return a;
},{}));

<强>演示

var 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
  }
];

var output = Object.values(fruits.reduce((a, c) => {
  a[c.year] = a[c.year] || {
    year: c.year
  };
  a[c.year]["total"] = (a[c.year]["total"] || 0) + 1;
  a[c.year][c.fruit] = (a[c.year][c.fruit] || 0) + 1;
  return a;
}, {}));

console.log(output);

答案 1 :(得分:1)

您可以使用array#reduce根据年份对数据进行分组,并计算对象累加器中的水果出现次数。然后使用Object.values()

从此对象获取所有值

&#13;
&#13;
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 } ],
    result = Object.values(fruits.reduce((r,{fruit, year}) => {
      r[year] = r[year] || {year};
      r[year][fruit] = (r[year][fruit] || 0) + 1;
      r[year]['total'] = (r[year]['total'] || 0) + 1;
      return r;
    },{}));
console.log(result);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以使用数组作为结果集,它保持年份的给定顺序。

&#13;
&#13;
var 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 }],
    result = fruits.reduce((r, { year, fruit }) => {
        var item = r.find(o => o.year === year);
        if (!item) {
            r.push(item = { year });
        }
        item[fruit] = (item[fruit] || 0) + 1;
        return r;
    }, []);
    
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;