how can group UTC dates by date YYY-MM-DD?
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
}