I have an existing sales array with various sale objects. I would like to loop through the array and create arrays where all my sale objects are grouped according to the sales date. I'm not sure if it's possible or what array method i should use
CodePudding user response:
You could use reduce
for grouping
const sales = [
{ date: "2022-02-03", info: "Lorem ipsum dolor sit" },
{ date: "2022-02-01", info: "amet consectetur adipisicing elit" },
{ date: "2022-02-03", info: "Suscipit consequatur, temporibus repellendus" },
{ date: "2022-02-05", info: "deserunt quaerat eos officiis" },
{ date: "2022-02-01", info: "molestiae explicabo possimus obcaecati fuga" },
{ date: "2022-02-03", info: "Fugiat soluta repudiandae quod" },
];
const groupedSales = sales.reduce((acc, el) => {
if (!acc[el.date]) {
acc[el.date] = [];
}
acc[el.date].push(el);
return acc;
}, {});
console.log(groupedSales);