6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

lodash で groupBy を複数の値でしたい

Posted at

やりたいこと

以下のデータを id,name の二つの項目の組み合わせで groupBy したい

const data = [
  { id: '111', name: 'A', score: 100 },
  { id: '111', name: 'B', score: 50 },
  { id: '222', name: 'C', score: 100 },
  { id: '222', name: 'C', score: 50 },
  { id: '222', name: 'D', score: 70 }
];

こんな形にしたい

[
  { id: '111', name: 'A', sum: 100 },
  { id: '111', name: 'B', sum: 50 },
  { id: '222', name: 'C', sum: 150 },
  { id: '222', name: 'D', sum: 70 }
];

コード

実際できたコードはこちら

const _ = require('lodash');

const data = [
  { id: '111', name: 'A', score: 100 },
  { id: '111', name: 'B', score: 50 },
  { id: '222', name: 'C', score: 100 },
  { id: '222', name: 'C', score: 50 },
  { id: '222', name: 'D', score: 70 }
];

const groups = _.groupBy(data, value => {
  return value.id + '#' + value.name;
});

const result = _.map(groups, group => {
  return {
    id: group[0].id,
    name: group[0].name,
    sum: _.sumBy(group, 'score')
  };
});

console.table(result);
6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?