3👍
✅
Instead of using a single key
as parameter, you can get array of keys. Then create a unique key based on the values for each of those keys separated by a |
.
groupBy: function(array, keys){
const result = {};
array.forEach(item => {
// get an array of values and join them with | separator
const key = keys.map(k => item[k]).join('|');
// use that unique key in result
if (!result[key]){
result[key] = []
}
result[key].push(item)
});
return result
}
For the object you’ve posted, the unique key would look like this:
Gecultiveerde paddestoelen|Shii-take|Medium
Here’s a snippet:
function groupBy (array, keys){
const result = {};
array.forEach(item => {
const key = keys.map(k => item[k]).join('|');
if (!result[key]){
result[key] = []
}
result[key].push(item)
});
return result
}
const input=[{Class:"Gecultiveerde paddestoelen",Soort:"Shii-take",Sortering:"Medium",LvH:"SP",Omschrijving:"SHIITAKE MEDIM STEMLESS unclosed","Trade unit composition":"8 x 150gr","Punnet type":"CARTON","CONTAINER BOX":"Multicrate (30x40x11)","Price (/box)":"10","Amount (container box) per Pallet / Europallet \r":"200 / 160\r"}];
console.log(groupBy(input, ['Class', 'Soort', 'Sortering']))
Source:stackexchange.com