1

I want to arrange the data which I am getting from the API according to the time. Here is one of the objects inside the array.

{
    "orderId": "xxxxxxxxxxxxx",
    "amount": 10,
    "status": "CREATED",
    "transactionTime": 1651498914,
    "type": "ADD",
    "mode": "UPI",
    "bankAccountId": {
        "bankAccountNumber": "xxxxxxxxxxxxx",
        "ifsc": "XXXX XXXX XXXX"
    }
}

I want to arrange the array in descending order according to the transactionTime which is an epoch time.

My initial approach.

data.map((item) => item.transactionTime)
   .sort()
   .reverse()
   .map((item) => {
        return data.find((i) => i.transactionTime == item);
})

This code is perfectly working but as you can see, it is not a good way to do this. So I want a more optimized solution. Someone suggested using a priority queue.

  • "which is an epoch time." -- isn't every time-and-date system an epoch-relative value? – Dai Jun 15 '22 at 14:01
  • `.map( e => Array.find( x => ) )` has **O(n^2)** runtime - don't do that. – Dai Jun 15 '22 at 14:02
  • 1
    All you need is `const sorted = Array.from( data ).sort( ( x, y ) => x.transactionTime - y.transactionTime );` – Dai Jun 15 '22 at 14:04

1 Answers1

-1

You can directly subtract the times in the sort callback.

data.sort((a, b)=>b.transactionTime - a.transactionTime);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80