这个数组怎么改,去重去之后算合计
[ {"name":'a',value:1},
{"name":'a',value:2},
{"name":'a',value:3},
{"name":'b',value:2},
{"name":'b',value:2},
{"name":'c',value:1},
]
怎么修改成
[ {"name":'a',value:6},
{"name":'b',value:4},
{"name":'c',value:1},
]
回答:
var arr = [{"name":'a',value:1},{"name":'a',value:2},
{"name":'a',value:3},
{"name":'b',value:2},
{"name":'b',value:2},
{"name":'c',value:1}];
var obj = arr.reduce((acc,cur)=>((acc[cur.name]= (acc[cur.name]||0) + cur.value),acc),{});
var res = Object.entries(obj).map(([name,value])=>({name,value}));
console.log(res);
var arr = [{"name":'a',value:1},{"name":'a',value:2},
{"name":'a',value:3},
{"name":'b',value:2},
{"name":'b',value:2},
{"name":'c',value:1}];
var obj = arr.reduce(function(acc,cur){
var item = acc[cur.name];
if(item){
item.value = item.value + cur.value;
} else {
acc[cur.name] = cur;
}
return acc;
},{});
var res = Object.values(obj);
console.log(res);
回答:
这个操作应该不叫去重再合计,应该叫做分类合计,或者分组合计。如果用 Lodash 来写,过程是先分组(变成对象),再合计值,再转换回数组:
const r = _(data) .groupBy("name")
.mapValues(value => _.sumBy(value, "value"))
.entries()
.map(([key, value]) => ({ name: key, value }))
.value();
也可以不用 Lodash,自己写个 reduce,逻辑很简单就是普通的循环和循环内查找:
const r = data.reduce((r, it) => { let found = r.find(rIt => rIt.name === it.name);
if (found) {
found.value += it.value;
} else {
found = { ...it };
r.push(found);
}
return r;
}, []);
回答:
function unique(arr) { var ret = [];
loop: for (var i = 0; i < arr.length; ++i) {
for (var j = 0; j < ret.length; ++j) {
if (ret[j].name === arr[i].name) {
ret[j].value += arr[i].value;
continue loop;
}
}
ret.push(arr[i]);
}
return ret;
}
console.dir(unique([
{ name: 'a', value: 1 },
{ name: 'a', value: 2 },
{ name: 'a', value: 3 },
{ name: 'b', value: 2 },
{ name: 'b', value: 2 },
{ name: 'c', value: 1 }
]));
以上是 这个数组怎么改,去重去之后算合计 的全部内容, 来源链接: utcz.com/p/936606.html