0

How could I sort something like this by the date field?

The array is a merged array from 2 different database tables, that I get as a JsonRespornce

[{id: 92, amount: 450, date: "2021-05-17", description: "fkeo", owner_id: 23, …}
{id: 93, amount: 490, date: "2021-05-17", description: "", owner_id: 23, …}
{id: 94, amount: 4775, date: "2021-05-16", description: "ghjgj", owner_id: 23, …}
{id: 13, amount: "420.00", date: "2021-05-17", description: "o", owner_id: 23, …}
{id: 14, amount: "450.00", date: "2021-05-17", description: "cdda", owner_id: 23, …}
{id: 15, amount: "460.00", date: "2021-05-15", description: "", owner_id: 23, …}]

I tried using something like this but it didn't work for

const sortedArray = array.sort((a, b) => b.date - a.date)

2 Answers2

0

const input = [{id: 92, amount: 450, date: "2021-05-17", description: "fkeo", owner_id: 23, },
{id: 93, amount: 490, date: "2021-05-17", description: "", owner_id: 23,},
{id: 94, amount: 4775, date: "2021-05-16", description: "ghjgj", owner_id: 23},
{id: 13, amount: "420.00", date: "2021-05-17", description: "o", owner_id: 23, },
{id: 14, amount: "450.00", date: "2021-05-17", description: "cdda", owner_id: 23, },
{id: 15, amount: "460.00", date: "2021-05-15", description: "", owner_id: 23}]

const output = input.sort((a, b) => new Date(a.date) - new Date(b.date))

console.log(output)
bel3atar
  • 754
  • 1
  • 5
0

You just need to make it a Date object using

new Date(a.date)

and then sort it using the comparator function.

const array = [{
    id: 92,
    amount: 450,
    date: "2021-05-17",
    description: "fkeo",
    owner_id: 23,
  },
  {
    id: 93,
    amount: 490,
    date: "2021-05-17",
    description: "",
    owner_id: 23
  },
  {
    id: 94,
    amount: 4775,
    date: "2021-05-16",
    description: "ghjgj",
    owner_id: 23,
  },
  {
    id: 13,
    amount: "420.00",
    date: "2021-05-17",
    description: "o",
    owner_id: 23,
  },
  {
    id: 14,
    amount: "450.00",
    date: "2021-05-17",
    description: "cdda",
    owner_id: 23,
  },
  {
    id: 15,
    amount: "460.00",
    date: "2021-05-15",
    description: "",
    owner_id: 23,
  },
];

const result = array.sort((a, b) => {
  return new Date(a.date) - new Date(b.date);
});

console.log(result);
decpk
  • 6,314
  • 1
  • 10
  • 24