I have an array of objects (old_array) that needs to be merged to become (new_array)
old_array = [
{ id: 'ffff55', name: 'f5', card: 'a', request: { device: 0, bus: 1, ship: 21 } },
{ id: 'vvvv44', name: 'v4', card: 'c', request: { device: 3, bus: 10, ship: 2 } },
{ id: 'cccc33', name: 'c3', card: 'a', request: { device: 0, bus: 1, ship: 2 } },
{ id: 'ffff55', name: 'f5', card: 'b', request: { device: 32, bus: 31, ship: 32 } },
{ id: 'cccc33', name: 'c3', card: 'e', request: { device: 21, bus: 21, ship: 22 } },
{ id: 'cccc33', name: 'c3', card: 'd', request: { device: 4, bus: 1, ship: 2 } },
{ id: 'vvvv44', name: 'v4', card: 'c', request: { device: 13, bus: 11, ship: 12 } }
];
new_array = [
{ id: 'ffff55', name: 'f5', unique_cards: 2, request: { device: 32, bus: 32, ship: 53 } },
{ id: 'vvvv44', name: 'v4', unique_cards: 1, request: { device: 16, bus: 21, ship: 14 } },
{ id: 'cccc33', name: 'c3', unique_cards: 3, request: { device: 25, bus: 23, ship: 26 } }
];
- merge the objects with same id and name to a single object
- merge the nested request object (Sum of its values)
- map card to the number of unique cards (by id)
I've been trying for 4 days straight but this array manipulation was hard
My best attempt was trying to group the array of objects by id but it become more complex with many redundant values
groupByArray(xs, key) {
return xs.reduce(function(rv, x) {
let v = key instanceof Function ? key(x) : x[key];
let el = rv.find((r) => r && r.key === v);
if (el) {
el.values.push(x);
} else {
rv.push({ key: v, values: [ x ] });
}
return rv;
}, []);
}
groupByArray(old_array , 'id')