Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

Grouping JavaScript array with sum

[ 

{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"},

]

I want to group by t_id and find the sum of val1 according to each t_id and divide the val1 by total number of t_id .... eg: there are three t-id 1 in the array and sum is of three t_id is 3(val1)..so the val1 must be 3/total t_id( ie 3/3)...

then i want out on my HTML like

Title:cash to purchase

bag:1 (ie(3/3)

Title:Offload

bag:4.5 (ie 9/2)

title:onroad

bag:5.5 (ie 11/2) ...were 2 is total t_id

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...