Jessie
Jessie

Reputation: 493

How to sort array of object by key?

I tried this method:

if (field == 'age') {

      if (this.sortedAge) {
        this.fltUsers.sort(function (a, b) {
          if (b.totalHours > a.totalHours) {
            return 1;
          }
        });

        this.sortedAge = false;

      } else {

        this.sortedAge = true;
        this.fltUsers.sort(function (a, b) {
          if (b.totalHours < a.totalHours) {
            return 1;
          }
        });

      }
    }

So I have array of objects. Each object has property: totalHours.

I need to order this array by desc/asc this field totalHours after click.

My code does not work.

Upvotes: 0

Views: 1198

Answers (2)

Hoang Duc Nguyen
Hoang Duc Nguyen

Reputation: 409

I usually follow 1-line rule for the kind of simple comparator like yours, so I would modify it like this

this.fltUsers.sort((a,b) => b.totalHours < a.totalHours ? 1 : -1);

You need at least 1 and -1 returned so that the comparator logic can work.

Upvotes: 4

Nikola Andreev
Nikola Andreev

Reputation: 634

This code must sort the array.

  function compare(a,b) {
      if (b.totalHours < a.totalHours)
        return -1;
      if (b.totalHours > a.totalHours)
        return 1;
      return 0;
  }

  objects.sort(compare);

Upvotes: 2

Related Questions