Clore Nora
Clore Nora

Reputation: 137

Sort an array in ascending order - React js

I'm trying to sort my array. I want to have the lowest "time" element in first, and the biggest "time" element in last.

[
  {
    "Payload": {
      "humidity": 32,
      "time": 1610877284,
    },
    "time": "1610877284",
    "PositionInRow ": "{raw}"
  },
  {
    "Payload": {
      "humidity": 33,
      "time": 1610876854,
    },
    "time": "1610876854",
    "PositionInRow ": "{raw}"
  },
  {
    "Payload": {
      "humidity": 31,
      "time": 1610877588,
    },
    "time": "1610877588",
    "PositionInRow ": "{raw}"
  },
  {
    "Payload": {
      "humidity": 36,
      "time": 1610877462,
    },
    "time": "1610877462",
    "PositionInRow ": "{raw}"
  }
]

I wanted to use "array.sort((a, b) => a - b)" but it’s not possible with this type of array. Anyone have any idea of a function that can sort my array in ascending order ("time") ?

Upvotes: 0

Views: 427

Answers (1)

Kishor
Kishor

Reputation: 450

You can simply modify the function like this:

array.sort((a, b) => a.time - b.time)

Upvotes: 1

Related Questions