i want the result below
Given an array
[{
"date": "JAN",
"value": 5,
"weight": 3
}, {
"date": "JAN",
"value": 4,
"weight": 23
}, {
"date": "FEB",
"value": 9,
"weight": 1
}, {
"date": "FEB",
"value": 10,
"weight": 30
}]
and a key 'date'
transform it into following output:
[{
"date": "JAN",
"value": [5, 4],
"weight": [3, 23]
}, {
"date": "FEB",
"value": [9, 10],
"weight": [1, 30]
}]
any help would be much appreciated thank You in advance
Array#reduce, iterate over the array while updating a Map where the primaryKey is the key and the grouped object is the valueObject#entries, get the list of pairs from the propertiesMap#get, get the current primary-key value if existsArray#forEach and update the arraysMap#setMap#values, you can get the list of grouped objectsconst transform = (arr, primaryKey) =>
[...
arr.reduce((map, e) => {
const { [primaryKey]: key, ...props } = e;
const currentProps = Object.entries(props);
const item = map.get(key);
if(item) {
currentProps.forEach(([ k, v ]) => item[k] = [...(item[k] ?? []), v]);
} else {
const obj = currentProps.reduce((acc, [ k, v ]) => ({
...acc, [k]: Array.isArray(v) ? [...v] : [v]
}), { primaryKey: key });
map.set(key, obj);
}
return map;
}, new Map)
.values()
];
console.log( transform([ { "date": "JAN", "value": 5, "weight": 3 }, { "date": "JAN", "value": 4, "weight": 23 }, { "date": "FEB", "value": 9, "weight": 1 }, { "date": "FEB", "value": 10, "weight": 30 } ], 'date') );
console.log( transform([ { type: '200', api: [ '/counter' ] }, { type: '400', api: [ '/counter' ] }, { type: '500', api: [ '/counter', '/product' ] } ], 'type') );