Javascript New GroupBy
1 min readOct 6, 2023
hello everyone today we will talk about new javascript properties Object.groupBy.
Integration
Before Object.groupBy we should have grouped like this
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];
function groupByType(inventory) {
const groupedInventory = {};
inventory.forEach(item => {
const { type, ...rest } = item;
if (!groupedInventory[type]) {
groupedInventory[type] = [];
}
groupedInventory[type].push(rest);
});
return groupedInventory;
}
const groupedByType = groupByType(inventory);
console.log(groupedByType);
as you can see there is too much code here, but now we can convert it to this
const inventory = [
{ name: "asparagus", type: "vegetables", quantity: 5 },
{ name: "bananas", type: "fruit", quantity: 0 },
{ name: "goat", type: "meat", quantity: 23 },
{ name: "cherries", type: "fruit", quantity: 5 },
{ name: "fish", type: "meat", quantity: 22 },
];
const result = Object.groupBy(inventory, ({ type }) => type);
console.log(result);
this is a new javascript property for group actions.
☕ Buy me Coffee : https://buymeacoffee.com/yasindlklcc
Good work everyone.