0

can anybody help me sorting this array of objects by date.

[{ date: "Dienstag, 07.07.20", time: "09:15", id: "18685672", … }
, { date: "Dienstag, 07.07.20", time: "13:10", id: "18685668", … }
, { date: "Freitag, 10.07.20", time: "12:05", id: "18685736", … }
, { date: "Montag, 06.07.20", time: "10:10", id: "18685684", … }
, { date: "Montag, 06.07.20", time: "14:05", id: "18685652", … }
, { date: "Donnerstag, 09.07.20", time: "14:10", id: "18685718", …}]
ange408
  • 23
  • 2
  • 3
    Does this answer your question? [How to sort an array by a date property](https://stackoverflow.com/questions/10123953/how-to-sort-an-array-by-a-date-property) – halilcakar Jul 03 '20 at 08:54
  • The thing is you don't have date objects, these are just strings that you would have to parse into dates. – Rob Jul 03 '20 at 08:58
  • Say the array is in `arr`. then: `arr.sort((a,b)=>{ aa=a.date.split(" ")[1].split(".").reverse().join(".")+a.time; bb=b.date.split(" ")[1].split(".").reverse().join(".")+b.time; return aa – iAmOren Jul 03 '20 at 09:11

2 Answers2

1

You could get an ISO 8601 string and sort by string.

const getISO = o => {
    const [d, m, y] = o.date.match(/.{8}$/)[0].split('.');
    return `20${y}-${m}-${d} ${o.time}`;
};

var data = [{ date: "Dienstag, 07.07.20", time: "09:15", id: "18685672" }, { date: "Dienstag, 07.07.20", time: "13:10", id: "18685668" }, { date: "Freitag, 10.07.20", time: "12:05", id: "18685736" }, { date: "Montag, 06.07.20", time: "10:10", id: "18685684" }, { date: "Montag, 06.07.20", time: "14:05", id: "18685652" }, { date: "Donnerstag, 09.07.20", time: "14:10", id: "18685718" }];

data.sort((a, b) => getISO(a).localeCompare(getISO(b)));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Say the array is in arr. then:

arr.sort((a,b)=>{
  aa=a.date.split(" ")[1].split(".").reverse().join(".")+a.time;
  bb=b.date.split(" ")[1].split(".").reverse().join(".")+b.time;
  return aa<bb?-1:aa==bb?0:1;
})

I'm assuming your date is NORMAL like anywhere in THE WORLD: dayOfMonth.Month.Year, unlike the silliness in USA where month comes BEFORE dayOfMonth, such as: "The 4th of July is celebrated on July 4th"... :)

iAmOren
  • 2,760
  • 2
  • 11
  • 23