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
JavaScript
x
19
19
1
let arr = [
2
{
3
Date: "2021-05-01",
4
Status: "incomplete",
5
},
6
{
7
Date: "2021-05-07",
8
Status: "incomplete",
9
},
10
{
11
Date: "2021-05-31",
12
Status: "Complete",
13
},
14
{
15
Date: "2021-05-31",
16
Status: "incomplete",
17
},
18
];
19
I want to convert this result like below, NOTE : Based on Date.
JavaScript
1
22
22
1
finalResult = [
2
{
3
Date: "2021-05-01",
4
Incompleted: 1,
5
Completed: 0,
6
Total: 1,
7
},
8
{
9
Date: "2021-05-07",
10
Incompleted: 1,
11
Completed: 0,
12
Total: 1,
13
},
14
{
15
Date: "2021-05-31",
16
Incompleted: 1,
17
Completed: 1,
18
Total: 2,
19
},
20
];
21
22
THANK YOU FOR YOUR CONTRIBUTION
Advertisement
Answer
You could make it dynamic for any number of status
.
- Create a
Set
ofstatus
to 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
group
object with eachDate
as the key and object needed in the output as its value.
JavaScript
1
14
14
1
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",}],
2
unique = new Set(arr.map(a => a.Status)),
3
initial = Object.fromEntries( Array.from(unique, s => [s, 0]) ),
4
group = { }
5
6
for (const { Date, Status } of arr) {
7
group[Date] ||= { Date, initial, Total: 0 };
8
group[Date][Status]++;
9
group[Date].Total++
10
}
11
12
const output = Object.values(group)
13
14
console.log( output )