Skip to content

How to aggregate an array of objects based on object property

Mathias Rangel Wulff edited this page Jun 13, 2015 · 2 revisions

How to aggregate an array of objects based on object property?

Source: StackOverflow.com

Question

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 },
      ...
      ...
    ]

Answer

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 ]);
Clone this wiki locally