Basically i know array, and it’s prototype methods, I tried to get the result by using new Set(), map and filter. but somehow i stuck at some point to get the desired result.
Below are the details about the problem and how i want the result.
Result I’m Getting
let arr = [
{
Date: "2021-05-01",
Status: "incomplete",
},
{
Date: "2021-05-07",
Status: "incomplete",
},
{
Date: "2021-05-31",
Status: "Complete",
},
{
Date: "2021-05-31",
Status: "incomplete",
},
];
I want to convert this result like below, NOTE : Based on Date.
finalResult = [
{
Date: "2021-05-01",
Incompleted: 1,
Completed: 0,
Total: 1,
},
{
Date: "2021-05-07",
Incompleted: 1,
Completed: 0,
Total: 1,
},
{
Date: "2021-05-31",
Incompleted: 1,
Completed: 1,
Total: 2,
},
];
THANK YOU FOR YOUR CONTRIBUTION
Advertisement
Answer
You could make it dynamic for any number of status.
- Create a
Setofstatusto get all the unique status - Create a partial object with all status as key and 0 as their value. There are many ways to create it. I’m using
Object.fromEntries. It will look like this:{ "incomplete": 0, "Complete": 0 } - Loop through the array. Use a
groupobject with eachDateas the key and object needed in the output as its value.
const arr = [{Date:"2021-05-01",Status:"incomplete",},{Date:"2021-05-07",Status:"incomplete",},{Date:"2021-05-31",Status:"Complete",},{Date:"2021-05-31",Status:"incomplete",}],
unique = new Set(arr.map(a => a.Status)),
initial = Object.fromEntries( Array.from(unique, s => [s, 0]) ),
group = { }
for (const { Date, Status } of arr) {
group[Date] ||= { Date, ...initial, Total: 0 };
group[Date][Status]++;
group[Date].Total++
}
const output = Object.values(group)
console.log( output )