[Solved] Grouping JavaScript array with sum


Do it like this:

var array = [{t_id:"1",val1:"1",title:"cash to purchase",unit:"bag"},{t_id:"1",val1:"1",title:"cash to purchase",unit:"bag"},{t_id:"1",val1:"1",title:"cash to purchase",unit:"bag"},{t_id:"2",val1:"4",title:"offload",unit:"bag"},{t_id:"2",val1:"5",title:"onroad",unit:"bag"},{t_id:"3",val1:"5",title:"Onroad",unit:"bag"},{t_id:"3",val1:"6",title:"Onroad",unit:"bag"}];


var grouped = [];

array.forEach(function(o) {
  var count = 0;
  if (!this[o.t_id]) {
    this[o.t_id] = {
      t_id: o.t_id,
      val1: 0,
      title: o.title,
      counter: count
    };
    grouped.push(this[o.t_id]);
  }
  this[o.t_id].val1 += Number(o.val1);
  this[o.t_id].counter += Number(++count);
}, Object.create(null));

console.log(grouped);

Now in HTML show like this : Bag: {{result.val1/result.counter}}

5

solved Grouping JavaScript array with sum