0

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.

2
  • 2
    This is hard to tell without actually seeing the array, it's also most likely a duplicate. Anyway, you're only returning if something happens, you should be returning 1, -1 or 0 depending on the comparison. Commented Jan 13, 2018 at 14:38
  • this.fltUsers.sort((a, b) => a.totalHours - b.totalHours) Commented Jan 13, 2018 at 14:49

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.