I have the following array
var dic = [
{user:'John', notifications:[{created: 'Wed Jan 12 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Bob', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'},
{created: 'Wed Feb 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Ron', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'xxx', notifications:[{created: 'Wed Jan 31 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
]
My goal is to sort by date all notifications - the finale result should be like the following - "Bob" should be the first since he got the higher date (Feb 15)
var dic = [
{user:'Bob', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'},
{created: 'Wed Feb 15 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'John', notifications:[{created: 'Wed Jan 12 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Bob', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'},
{created: 'Wed Feb 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Ron', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
]
I've tried to sort it like in the example - but i didn't manage to succeed.
var dic = [
{user:'John', notifications:[{created: 'Wed Jan 12 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Bob', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}, {created: 'Wed Feb 15 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'Ron', notifications:[{created: 'Wed Jan 01 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
{user:'xxx', notifications:[{created: 'Wed Jan 31 2023 11:58:24 GMT+0200 (Israel Standard Time)'}]},
]
dic.sort((a,b) => {
//console.log('a', a, 'b', b);
if(a.notifications.length > 1){
const test = a.notifications.reduce((a,b) => new Date(a.created).getTime() >= new Date(b.created).getTime() ? a.created : b.created);
return new Date(test).getTime() >= new Date(b.notifications[0].created).getTime() ? -1 : 1;
} else{
return new Date(a.notifications[0].created).getTime() <= new Date(b.notifications[0].created).getTime() ? -1 : 1;
}
})
console.log(dic)