I have an array of utc dates like:
[
{createdAt: '2022-01-19T22:15:33.008Z'},
{createdAt: '2022-01-19T21:15:33.008Z'},
{createdAt: '2022-01-19T10:15:33.008Z'},
{createdAt: '2022-01-20T23:15:33.008Z'},
{createdAt: '2022-01-21T23:15:33.008Z'},
{createdAt: '2022-01-22T23:15:33.008Z'},
{createdAt: '2022-01-18T23:15:33.008Z'},
]
My desired output is:
{
"2022-01-19":[
{createdAt: '2022-01-19T22:15:33.008Z'},
{createdAt: '2022-01-19T21:15:33.008Z'},
{createdAt: '2022-01-19T10:15:33.008Z'}
],
"2022-01-20":[
{createdAt: '2022-01-20T23:15:33.008Z'},
],
"2022-01-21":[
{createdAt: '2022-01-21T23:15:33.008Z'},
],
"2022-01-22":[
{createdAt: '2022-01-22T23:15:33.008Z'},
],
"2022-01-18":[
{createdAt: '2022-01-18T23:15:33.008Z'},
],
}
I don't know if there is any date management function to get the YYYYY-MM-DD of a timestamp. how can I do it?
let tab = [
{createdAt: '2022-01-19T22:15:33.008Z'},
{createdAt: '2022-01-19T21:15:33.008Z'},
{createdAt: '2022-01-19T10:15:33.008Z'},
{createdAt: '2022-01-20T23:15:33.008Z'},
{createdAt: '2022-01-21T23:15:33.008Z'},
{createdAt: '2022-01-22T23:15:33.008Z'},
{createdAt: '2022-01-18T23:15:33.008Z'},
]
let output = {};
tab.forEach(element => {
let date = element.createdAt.split('T')[0];
if (output[date] == undefined) {
output[date] = []
}
output[date].push(element)
});
console.log(output)
You can split the string by the character 'T', then get the first item in the array to convert the string into the correct format.
Then, you can use Array.reduce to construct the object:
let arr = [
{createdAt: '2022-01-19T22:15:33.008Z'},
{createdAt: '2022-01-19T21:15:33.008Z'},
{createdAt: '2022-01-19T10:15:33.008Z'},
{createdAt: '2022-01-20T23:15:33.008Z'},
{createdAt: '2022-01-21T23:15:33.008Z'},
{createdAt: '2022-01-22T23:15:33.008Z'},
{createdAt: '2022-01-18T23:15:33.008Z'},
]
const res = arr.reduce((a,b) => {
let date = b.createdAt.split("T")[0];
if(!a[date]){
a[date] = [];
}
a[date].push(b);
return a;
}, {})
console.log(res)
.as-console-wrapper {
max-height: 100%!important;
top: 0
}