I have referred to this article
I have the following code:
var testArrys = [
{ attrName: 'life', p_id:19, num:1, name: 'milk'},
{ attrName: 'food', p_id:20, num:1, name: 'apple'},
{ attrName: 'life', p_id:19, num:2, name: 'milk'},
{ attrName: 'life', p_id:22, num:1, name: 'egg'},
{ attrName: 'clothes', p_id:21, num:1, name: 'coat'},
]
Divide the different arrays according to attrName, add num according to whether p_id is the same, Delete more than p_id objects
I tried the following:
function groupBy(list, keyGetter) {
const map = new Map();
list.forEach((item) => {
const key = keyGetter(item);
const collection = map.get(key);
if (!collection) {
map.set(key, [item]);
} else {
collection.push(item);
}
});
return map;
}
const grouped = groupBy(testArrys, attr => attr.attrName);
I tried, but I couldn't achieve what I wanted
I want the following results:
var result = [
[
{ attrName: 'life', p_id:19, num:3, name: 'milk'},
{ attrName: 'life', p_id:22, num:1, name: 'egg'},
],
[
{ attrName: 'food', p_id:20, num:1, name: 'apple'}
],
[
{ attrName: 'clothes', p_id:21, num:1, name: 'coat'}
],
]