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

Categories

[ 

{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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...