3

I have array of following class

export class Tests {
  id: number;
  name: string;
  createdAt: any;
  succress: boolean;

  constructor(id: number, name: string, createdAt: any, success: boolean) {
    this.id = id;
    this.name = name;
    this.createdAt = createdAt;
    this.succress = success;
  }
}

And I want to sort it by value of success (false on top and true on bottom). How can I do that?

I've tried

this.tests.sort((a,b)=> b.succress - a.succress);

But is not doing anything

3 Answers 3

4

You can sort by boolean value as follows:

this.tests.sort((a, b) => {
   if (a.succress === b.succress) {
      return 0;
   }

   if (a.succress) {
      return -1;
   }

   if (b.succress) {
      return 1;
   }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Nitpicking here but would it not be more correct to first check if a === b return 0 if a === true return -1 then return 1. Now when a and b are the same it would return 1 or -1 which is incorrect.
1

Maybe something like this?

[false,true,false,true]
.sort(
  (a,b)=>
    (a===b)?0
    :(a===true)?1:-1)

Comments

0

You can easily achieve this using lodash sortBy function

_.sortBy(this.users,['succress'])

LIVE DEMO

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.