Given this array of objects:
[
{"Code": 101, "Description": "Invoice"},
{"Code": 102, "Description": "Credit"},
{"Code": 103, "Description": "Credit"},
{"Code": 111, "Description": "Invoice"},
{"Code": 112, "Description": "Credit"},
{"Code": 113, "Description": "Credit"},
{"Code": 182, "Description": "Backup"}
]
I need to combine the objects that have matching Description
s into one single object with an array of Code
s, like so:
[
{"Code": [101,111], "Description": "Invoice"},
{"Code": [102,103,112,113], "Description": "Credit"},
{"Code": [182], "Description": "Backup"}
]
I have tried with the groupBy()
helper function below (the vanilla JS one) and it is not working because I get an Object
with a single undefined
property with the original array as it's value:
var groupBy = function (arr, criteria) {
return arr.reduce(function (obj, item) {
// Check if the criteria is a function to run on the item or a property of it
var key = typeof criteria === 'function' ? criteria(item) : item[criteria];
// If the key doesn't exist yet, create it
if (!obj.hasOwnProperty(key)) {
obj[key] = [];
}
// Push the value to the object
obj[key].push(item);
// Return the object to the next item in the loop
return obj;
}, {});
};
var array = [
{"Code": 101, "Description": "Invoice"},
{"Code": 102, "Description": "Credit"},
{"Code": 103, "Description": "Credit"},
{"Code": 111, "Description": "Invoice"},
{"Code": 112, "Description": "Credit"},
{"Code": 113, "Description": "Credit"},
{"Code": 182, "Description": "Backup"}
];
var groupDescription = groupBy(array, array.forEach(document => document.Description));
console.log(groupDescription);
What would be the best way to achieve my expected output?