javascript - Summarizing data for JSON -
{id:1, val:'author', hits:1}, {id:1, val:'author', hits:2}, {id:1, val:'reviewer', hits:1}, {id:2, val:'author', hits:100}, {id: 1, val:'author', hits:5}
etc.
i want aggregates data (can javascript, jquery, or angular filters single loop)
{id: 1, author:3, reviewer:1, hits:9 } {id: 2, author:1, reviewer:0, hits:100}
breaking head on bit now!!
one possible approach:
var source = [ {id:1, val:'author', hits:1}, {id:1, val:'author', hits:2}, {id:1, val:'reviewer', hits:1}, {id:2, val:'author', hits:100}, {id: 1, val:'author', hits:5} ]; var grouped = source.reduce(function(dict, el, i, arr) { var obj = dict[el.id]; if (!obj) { obj = { id: el.id, author: 0, reviewer: 0, hits: 0 }; dict.__arr.push(obj); dict[el.id] = obj; } obj[el.val]++; obj.hits += el.hits; return === arr.length - 1? dict.__arr : dict; }, {__arr:[]});
demo. often, when need group items criteria, use array.reduce
dictionary object organize grouping process. in case, it's bit more complicated because need resulting array single loop; dictionary object supplied specific property ('__arr') that's filled while dictionary constructed. in end (checked i === arr.length - 1
) array given out result of .reduce.
Comments
Post a Comment