面试题中往往会遇到这样的笔试题,将以下数组对象合并相同值
var arr = [{
"name": "语文",
"fraction": 80
}, {
"name": "数学",
"fraction": 70
}, {
"name": "语文",
"fraction": 50
}, {
"name": "语文",
"fraction": 90
}, {
"name": "数学",
"fraction": 100
}, {
"name": "数学",
"fraction": 55
}, {
"name": "语文",
"fraction": 99
}]
在实际项目中,我们经常会遇到这种格式的数据,这种格式让人阅读起来很不直观,而且不利于代码的维护。废话不多说了直接上代码
第一种方式:
arr = arr.map(function(item, index, arr) {
const i = arr.find(_item => item.name === _item.name);
if(i !== item) {
i.fraction.push(item.fraction);
return undefined;
} else {
i.fraction = [i.fraction];
return i;
}
}).filter(item => item !== undefined);
输出结果:
[{
"name": "语文",
"fraction": [80, 50, 90, 99]
}, {
"name": "数学",
"fraction": [70, 100, 55]
}, {
"name": "英语",
"fraction": [55, 89]
}]
第二种方式:推荐
var res =[];
var narr=[];
for(var i =0;i<arr.length;i++){
var n = res.indexOf(arr[i].name);
if(n == -1){
res.push(arr[i].name);
narr.push({"name":arr[i].name,fraction:[arr[i].fraction]})
}else{
narr[n].fraction.push(arr[i].fraction)
}
}
console.log(narr)
标签:arr,数组,相同,55,合并,语文,item,fraction,name From: https://www.cnblogs.com/Ao-min/p/16911127.html输出结果: [{ "name": "语文", "fraction": [80, 50, 90, 99] }, { "name": "数学", "fraction": [70, 100, 55] }, { "name": "英语", "fraction": [55, 89] }]
转自于:https://www.csdn.net/tags/MtjaUgwsMDEwMDUtYmxvZwO0O0OO0O0O.html