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.

Mario Petrovic
  • 7,500
  • 14
  • 42
  • 62
devraj
  • 9
  • 1
  • 2
    Please be aware the above is not JSON. – evolutionxbox Jan 18 '22 at 13:12
  • Have a look at this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort you can achieve it in one line if you try – A. Llorente Jan 18 '22 at 13:17
  • Does this answer your question? [How to sort an object array by date property?](https://stackoverflow.com/questions/10123953/how-to-sort-an-object-array-by-date-property) – mo3n Jan 18 '22 at 13:22

3 Answers3

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

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

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();
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)));
Prathap Parameswar
  • 489
  • 1
  • 3
  • 11