CarComp
CarComp

Reputation: 2016

How does one sort an array of same objects by a sub property?

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.

Upvotes: 0

Views: 64

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386680

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

Upvotes: 0

Magnus
Magnus

Reputation: 1421

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

Upvotes: 4

Related Questions