0

I have an array of items as follows:

myarray = [
    {
      somedate: "2018-01-11T00:00:00",
      name: "John Doe",
      level: 6000
    },
    {
      somedate: "2017-12-18T00:00:00",
      name: "Don Jhoe",
      level: 53
    },
    {
      somedate: "2016-12-18T00:00:00",
      name: "Jane Doe",
      level: 100
    },
    {
      somedate: "2018-10-18T00:00:00",
      name: "Dane Joe",
      level: 1
    }
]

I'm trying to figure out how to sort this array so that it is sorted by date. I know how to sort an array of simple properties:

Sort Javascript Object Array By Date

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);
    });

But how is it best handled to sort an array by its items properties?

EDIT: Yes, those really are improper date strings provided by a strange web service that doesn't handle time.

CarComp
  • 1,742
  • 1
  • 18
  • 38
  • 1
    Its `somedate` not `date` – Nenad Vracar Jan 04 '19 at 13:10
  • 2
    Your example will work if you just change `a.date` to `a.somedate` and do the same for `b` – Titus Jan 04 '19 at 13:10
  • What do you mean by sub items? – kemicofa ghost Jan 04 '19 at 13:11
  • "*improper date strings*" - They might be lacking milliseconds and a timezone, but they are [valid date time strings](https://stackoverflow.com/questions/51715259/what-are-valid-date-time-strings-in-javascript/). As long as those date strings either all or none contain a timezone, it should work (otherwise you might run into problems with Safari). – str Jan 04 '19 at 13:13

2 Answers2

4

The code you've posted actually works just fine. All you need to do is compare somedate instead of date, and assign the final sort result to the original (if that is what is desired).

myarray = myarray.sort(function(a,b){
      return new Date(b.somedate) - new Date(a.somedate);
    });
Magnus Svensson
  • 410
  • 3
  • 11
0

By having an ISO 8601 compliant date, you could use a string comparer, because the organization of the values (year, month, day, hour, etc) is descending and have the same length for every unit.

var array = [{ somedate: "2018-01-11T00:00:00", name: "John Doe", level: 6000 }, { somedate: "2017-12-18T00:00:00", name: "Don Jhoe", level: 53 }, { somedate: "2016-12-18T00:00:00", name: "Jane Doe", level: 100 }, { somedate: "2018-10-18T00:00:00", name: "Dane Joe", level: 1 }];

array.sort(({ somedate: a }, { somedate: b }) => b.localeCompare(a)); // desc

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324