How do I sort array objects and manipulate them to return a new 2D array?

by BaiClassmate Xiao   Last Updated August 14, 2019 06:26 AM

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, and remove redundant 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'}
  ],
]
Tags : javascript


Related Questions


Updated March 15, 2017 04:26 AM

Updated May 20, 2017 20:26 PM

Updated February 05, 2018 07:26 AM

Updated July 28, 2019 07:26 AM

Updated October 25, 2017 02:26 AM