Suppose, we have a JSON array of objects like this −
const arr = [ { "id": "03868185", "month_10": 6, }, { "id": "03870584", "month_6": 2, }, { "id": "03870584", "month_7": 5, }, { "id": "51295", "month_1": 1, }, { "id": "51295", "month_10": 1, }, { "id": "55468", "month_11": 1, } ];
Here, we can see that the same "id" property is being repeated in some objects. We are required to write a JavaScript function that takes in one such array that contains all the key/value pairs for a specific "id" property grouped in one single object.
Example
The code for this will be −
const arr = [ { "id": "03868185", "month_10": 6, }, { "id": "03870584", "month_6": 2, }, { "id": "03870584", "month_7": 5, }, { "id": "51295", "month_1": 1, }, { "id": "51295", "month_10": 1, }, { "id": "55468", "month_11": 1, } ]; const groupById = (arr = []) => { const map = {}; const res = []; arr.forEach(el => { if(map.hasOwnProperty(el['id'])){ const index = map[el['id']] - 1; const key = Object.keys(el)[1]; res[index][key] = el[key]; } else{ map[el['id']] = res.push(el); } }) return res; }; console.log(groupById(arr));
Output
And the output in the console will be −
[ { id: '03868185', month_10: 6 }, { id: '03870584', month_6: 2, month_7: 5 }, { id: '51295', month_1: 1, month_10: 1 }, { id: '55468', month_11: 1 } ]