I have this dummy MySQL data:
id date (y/m/d) value
1 2022-1-1 random value
2 2022-2-5 random value
3 2022-3-3 random value
4 2022-4-6 random value
5 2022-5-11 random value
6 2022-6-7 random value
7 2022-7-16 random value
8 2022-8-4 random value
9 2022-9-7 random value
10 2022-10-8 random value
11 2022-11-4 random value
12 2022-12-9 random value
13 2023-1-2 random value
14 2023-2-4 random value
15 2023-3-22 random value
16 2023-4-5 random value
17 2023-5-8 random value
18 2023-6-19 random value
19 2023-7-12 random value
20 2023-8-4 random value
21 2023-9-2 random value
22 2023-10-10 random value
23 2023-11-21 random value
24 2023-12-27 random value
I want to achieve something like this:
[{
year:2022,
value:[
{
month:1,
value:[
{
day:1,
value:'random value'
}
]
},
{
month:2,
value:[
{
day:5,
value:'random value'
}
],
...
}
]
},{
year:2023,
value:[
...
]
}]
Is there anything that can sort something like this? I am using JavaScript, Node.js and I get an array of data like the dummy data from MySQL query. I have to sort it like this for frontend React.
I need something that is fast and not require a lot of processing because this operation will be done many times on the server.
Do you have any ideas?
Thank you in advance. 🙂
2
Answers
You could take an object for grouping and get a nested structure by taking parts of the date.
Those look like dates. Think about date arithmetic:
will generate one random date within 1000 days after the start of 2020. (Note there may be dups, but they could be dealt with afterward.)
This technique will generate Jan 31, but not Feb 31. It looks like your approach leads to losing Jan 31 or creating Feb 31.
Also, your data looks like you want one day per month. Is that a requirement. If so, please state. (My technique does not lend itself to such.)