1

I have a lot of data like this and i need to sort all data how can i do sort data?

Example

[
    {
        "date":159,
        "content":"blablabla"
    },
    {
        "date":null,
        "content":"blablabla"
    },
    {
        "date":7895,
        "content":"blablabla"
    }
]

how can i sort like this;

[
    {
        "date":null,
        "content":"blablabla"
    },
    {
        "date":159,
        "content":"blablabla"
    }
    {
        "date":7895,
        "content":"blablabla"
    }
]
GreXLin85
  • 97
  • 1
  • 10
  • 3
    What have you tried, and what exactly is the problem with it? – jonrsharpe Nov 22 '20 at 19:42
  • Take a look at [.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) however as Jon said, you should provide at least an attempt. – basic Nov 22 '20 at 19:44
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value) – Ivar Nov 22 '20 at 19:53

3 Answers3

2

This should work

json.sort(function(a, b){
    return a.date - b.date;
});
Aleksandar
  • 460
  • 3
  • 13
1

You cant use sort and since it looks like you're attempting to sort by a date, convert the value into a date object.

const data = [
  {
    "date":159,
    "content":"blablabla"
  },
  {
    "date":null,
    "content":"blablabla"
  },
  {
    "date":7895,
    "content":"blablabla"
  }
]

data.sort((a,b) => {
  return new Date(a.date) - new Date(b.date)
})
Matthew Moran
  • 1,457
  • 12
  • 22
  • No need to turn those values into `Date` objects. Subtracting will turn both operands back into the value you passed to them. (Not to mention that 159 and 7895 seem too small to represent the number of milliseconds since 1970, which the value that is passed to the Date constructor.) – Ivar Nov 22 '20 at 20:12
1

Try the sort method and sort after the date prop:

data.sort((a, b) => a.date - b.date);
Gabriel Lupu
  • 1,397
  • 1
  • 13
  • 29