需求:将同样类型的年龄相加
var arr = [{"type":"1","age":"20"},{"type":"2","age":"10"},{"type":"3","age":"50"},{"type":"2","age":"20"},{"type":"1","age":"15"},{"type":"20","age":"10"},{"type":"13","age":"70"},{"type":"3","age":"8"}];
实现方法
1、先找到所有的类型,然后根据类型去相加
var type = [];
for (var i = 0;i < arr.length; i++) {
var typevalue = arr[i].type;
var flag = 0;
for(var j = 0;j < type.length; j++){
if(typevalue==type[j]){
flag = 1;
}
}
if(flag==0){
type.push(typevalue);
}
}
var result = [];
for(var i = 0;i < type.length; i++){
var record = 0;
var typevalue = type[i];
for(var j = 0;j < arr.length; j++){
if(arr[j].type==typevalue){
record+=parseInt(arr[j].age);
}
}
var obj={};
obj[typevalue] = record;
result.push(obj);
}
console.log(result);
2、看此类型的在数组里有没有,如果有,则age相加,如果没有,则放进去(推荐)
var type = [];
var res = [];
for (var i = 0;i < arr.length; i++) {
var typevalue = arr[i].type;
var flag = 0;
for(var j = 0;j < type.length; j++){
if(typevalue==type[j]){
flag = 1;
res[j][typevalue] += parseInt(arr[i].age);
}
}
if(flag==0){
type.push(typevalue);
var obj = {};
obj[typevalue] = parseInt(arr[i].age);
res.push(obj);
}
}
网友评论