[
{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"},
]
我希望按t_id进行分组,并根据每个t_id找到val1的总和,并将val1除以t_id的总数....例如:数组中有三个t-id 1,总和为三个t_id是3(val1)..所以val1必须是3 /总t_id(即3/3)......
然后我想要我的HTML
标题:购买现金
包:1(即(3/3)
名称:卸载
包:4.5(即9/2)
标题:普通道路
包:5.5(即11/2)......总共2是t_id
答案 0 :(得分:1)
这样做:
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);
现在在HTML中显示如下:Bag: {{result.val1/result.counter}}
答案 1 :(得分:1)
我不知道下面的脚本是否适合你,但输出就像你想要的那样。
var sources = [
{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 groups = {};
for(var i in sources){
var source = sources[i];
if(typeof groups[source.t_id] !== 'undefined'){
groups[source.t_id].sum_of_val1 += Number(source.val1);
groups[source.t_id].num_of_items += 1;
}else{
groups[source.t_id] = source;
groups[source.t_id].sum_of_val1 = Number(source.val1);
groups[source.t_id].num_of_items = 1;
}
}
// print out put
for(var i in groups){
var group = groups[i];
document.write("Title: " + group.title + "<br/>Bag: " + (group.sum_of_val1 / group.num_of_items) + " (ie.: " + group.sum_of_val1 + " / " + group.num_of_items+ ")<br/><br/>");
}
&#13;