0
let array=[
    {
        "id": "a572963a1bcd0550c4cf8518624bcb92",
        "type": "car",
        "created": "2022-01-18 12:47:08"
    },
    {
        "id": "b84eb0fe1bc10550c4cf8518624bcb59",
        "type": "car",
        "created": "2022-01-18 06:23:39"
    },
    {
        "id": "a95b65fc1b898110c4cf8518624bcbee",
        "type": "bike",
        "created": "2022-01-12 04:30:16"
    },
    {
        "id": "5963929c1b018dd0c4cf8518624bcbc9",
        "type": "bike",
        "created": "2022-01-10 18:08:19"
    },
    {
        "id": "515b65fc1b898110c4cf8518624bcb91",
        "type": "bus",
        "created": "2022-01-12 04:30:16"
    },
    {
        "id": "7863929c1b018dd0c4cf8518624bcb52",
        "type": "bus",
        "created": "2022-01-10 18:08:17"
    }
]

I want sort the data from the above JSON array on the basis of date which is available in JSON as created. Pick only the latest created data.

3

3 Answers 3

1
array.sort((a,b) => a.created > b.created ? 1 : -1)

This should work if the created date string are in the same format

Sign up to request clarification or add additional context in comments.

Comments

0

To sort items by date property: Credit

array.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(b.date) - new Date(a.date);
});

then:

array.shift();

Comments

0

You can use sort function to sort it based on date value. One liner code will look like this

let sortedArray = array.sort((a, b)=> (new Date(b.created) - new Date(a.created)));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.