Suppose, we have an array of objects like this −
const arr = [ { 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' }, { 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' }, { 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' }, { 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' } ];
We are required to write a JavaScript function that takes in one such array of objects. The function should map remove the 'value' and 'type' keys from the objects and add their values as key value pairs to the respective objects.
Therefore, the output for the above input should look like this −
const output = [ { 'name': 'JON', 'flight':100, 'uns': 12, 'sch': 35 }, { 'name': 'BILL', 'flight':200, 'uns': 33, 'sch': 45} ];
Output
The code for this will be −
const arr = [ { 'name': 'JON', 'flight':100, 'value': 12, type: 'uns' }, { 'name': 'JON', 'flight':100, 'value': 35, type: 'sch' }, { 'name': 'BILL', 'flight':200, 'value': 33, type: 'uns' }, { 'name': 'BILL', 'flight':200, 'value': 45, type: 'sch' } ]; const groupArray = (arr = []) => { const res = arr.reduce(function (hash) { return function (r, o) { if (!hash[o.name]) { hash[o.name] = { name: o.name, flight: o.flight }; r.push(hash[o.name]); } hash[o.name][o.type] = (hash[o.name][o.type] || 0) + o.value; return r; } }(Object.create(null)), []); return res; }; console.log(groupArray(arr));
Output
And the output in the console will be −
[ { name: 'JON', flight: 100, uns: 12, sch: 35 }, { name: 'BILL', flight: 200, uns: 33, sch: 45 } ]