-
Notifications
You must be signed in to change notification settings - Fork 664
How to aggregate an array of objects based on object property
Mathias Rangel Wulff edited this page Jun 13, 2015
·
2 revisions
Source: StackOverflow.com
There is the following array of objects:
dataArray = [
{ id: "a", score: 1 },
{ id: "b", score: 2 },
{ id: "c", score: 5 },
...
{ id: "a", score: 3 },
...
{ id: "c", score: 2},
...
]
How can I obtain a resultArray like the following:
resultArray = [
{ id: "a", score: sum of all the scores when id is a },
{ id: "b", score: sum of all the scores when id is b },
...
...
]
You can do it in one line with AlaSQL library. See the example in jsFiddle.
var dataArray = [ { id: "a", score: 1 }, { id: "b", score: 2 }, { id: "c", score: 5 },
{ id: "a", score: 3 }, { id: "c", score: 2}, ];
var res = alasql('SELECT id, SUM(score) AS score FROM ? GROUP BY id',[dataArray ]);
© 2014-2024, Andrey Gershun & Mathias Rangel Wulff
Please help improve the documentation by opening a PR on the wiki repo