本文介绍了用总和对JavaScript数组分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
[
{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)...
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)...
然后我要在HTML上显示
then i want out on my HTML like
标题:购买现金
包:1(即(3/3)
标题:卸载
bag:4.5(即9/2)
bag:4.5 (ie 9/2)
title:onroad
title:onroad
bag:5.5(ie 11/2)...总共是t_id
bag:5.5 (ie 11/2) ...were 2 is total t_id
推荐答案
这样做:
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显示如下:包:{{result.val1 / result.counter}}
Now in HTML show like this : Bag: {{result.val1/result.counter}}
这篇关于用总和对JavaScript数组分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!