I am receiving data as an array of objects in JS. Each object has a value month and I want to show data with groups according to month. Example:
data: [
{id: 0001,month:2,desc:'objectone'},
{id: 0001,month:4,desc:'objecttwo'},
{id: 0001,month:4,desc:'objectthree'},
{id: 0001,month:4,desc:'objectfour'},
{id: 0001,month:5,desc:'objectfive'},
{id: 0001,month:5,desc:'objectsix'}
]
Now I want to show it like this:
<h1>Month {month}</h1>
<p>{desc}</p>
Month 2 objectone
Month 4 objecttwoo objectthree objectfour
Month 5 objectfive objectsix
I've used reduce to group it by the value but still having issue in mapping it to show as described above.
After reduce I get one object that contains array of objects:
data: {
1:(1) [{...}],
2:(3) [{...}],
3:(2) [{...}]
}
Thanks
After you've grouped the data you can loop through it using Object.entries and then inside the loop create the heading and the para for every month.
const data = [
{ id: "0001", month: 2, desc: "objectone" },
{ id: "0001", month: 4, desc: "objecttwo" },
{ id: "0001", month: 4, desc: "objectthree" },
{ id: "0001", month: 4, desc: "objectfour" },
{ id: "0001", month: 5, desc: "objectfive" },
{ id: "0001", month: 5, desc: "objectsix" },
];
const groups = data.reduce((r, d) => ((r[d.month] ??= []).push(d.desc), r), {});
Object.entries(groups).forEach(([mon, desc]) => {
const h2 = document.createElement("h2");
h2.textContent = `Month ${mon}`;
const p = document.createElement("p");
p.textContent = desc.join(" ");
document.body.appendChild(h2);
document.body.appendChild(p);
});