Skip to content

Instantly share code, notes, and snippets.

@npearce
Last active June 26, 2024 15:50
Show Gist options
  • Save npearce/ae04e54ce090ed76d1c01770de1cfc10 to your computer and use it in GitHub Desktop.
Save npearce/ae04e54ce090ed76d1c01770de1cfc10 to your computer and use it in GitHub Desktop.
Sort Array of JSON Object by date values
// Sort array of JSON objects by date value
const records = [
{
order_id: 12345,
order_date: "2020-03-23"
},
{
order_id: 12346,
order_date: "2020-03-20"
},
{
order_id: 12347,
order_date: "2020-03-22"
}
]
records.sort((a, b) => {
return new Date(a.order_date) - new Date(b.order_date); // descending
})
records.sort((a, b) => {
return new Date(b.order_date) - new Date(a.order_date); // ascending
})
@ArunaDhanapal
Copy link

Thanks much but how can I check if its sorted

@TanimSk
Copy link

TanimSk commented Jul 24, 2022

Thanks, brother! you saved my day!

@eniskastrati
Copy link

Very nice and clean way to handle it 👍

@kwhjvdkamp
Copy link

----ductionData.ts----JSON ARRAY WHICH NEED TO SORTED PROPERLY------
export const ductions: Iduction[] = [
{ 'Date': '2022-12-07', ... },
{ 'Date': '2022-12-08', ... },
{ 'Date': '2022-12-09', ... },
{ 'Date': '2022-12-10', ... },
];

----uploadDuctionData.ts----------------------------------------------------------
...
/** ! Presented example is WRONG

  • As time elevates it means the epoch-time (which is actually a number presentation)
  • grows each second with 1 (https://www.epochconverter.com/), right!
  • So, in case of descending sorting, the next substraction cycle need to
  • return a smaller number compared to the previous substraction
  • to obtain a list of decreasing epoch-times (numbers)
  • records.sort((a, b) => {
  • // => THIS NOT descending sorting... <=//
  • return new Date(a.order_date) - new Date(b.order_date);
  • // => ...it is 'ASCENDING' sorting <=//
  • }); */

// 👉️ Goal descending sorting on 'Date'-key of imported JSON array
// 👉️ 'hier (FR)' === 'yesterday (EN)'
ductions.sort((avantHier (a): Iduction, hier (b): Iduction) => {
const dayBeforeYesterDate = new Date(avantHier.Date (a));
const yesterdayDate = new Date(hier.Date (b));
// 👉️ Ascending sorting means 'dayBeforeYesterDate (avantHier.Date)' will be listed BEFORE younger dates
// return dayBeforeYesterDate.getTime() - yesterdayDate.getTime();
// 👉️ Descending sorting means 'yesterdayDate (hier.Date)' need to be listed BEFORE older dates
return yesterdayDate.getTime() - dayBeforeYesterDate.getTime(); // descending sorting
});
ductions.forEach(doc => console.log(JSON.stringify(doc)));
...


OUTPUT (terminal on 'uploadDuctionData.ts')
{"Date":"2022-12-27", ... }
{"Date":"2022-12-26", ... }
{"Date":"2022-12-25", ... }
{"Date":"2022-12-24", ... }

@grandgooroo
Copy link

Thx !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment