Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort by boolean value

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

like image 596
gsiradze Avatar asked May 07 '26 05:05

gsiradze


2 Answers

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;
   }
});
like image 75
Dieterg Avatar answered May 08 '26 18:05

Dieterg


Maybe something like this?

[false,true,false,true]
.sort(
  (a,b)=>
    (a===b)?0
    :(a===true)?1:-1)
like image 26
HMR Avatar answered May 08 '26 17:05

HMR



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!