Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort an array by a boolean property in typescript

I am using angular 10 and I was wondering how can I sort this array

var dic = [
  { state: false, id: 1 },
  { state: true, id: 2} ,
  { state: false, id: 3 },
  { state: true, id: 4 },
  { state: false, id: 5 }
]

I want to sort by the value of the boolean state, so the result goes this way:

[
  { state: true, id: 2 },
  { state: true, id: 4 },
  { state: false, id: 1 },
  { state: false, id: 3 },
  { state: false, id: 5 }
]

The true value goes first in the array.

What property or something from typescript I have to use to do that?

Thank you!

like image 966
Luis Bermúdez Avatar asked Sep 19 '25 09:09

Luis Bermúdez


2 Answers

You can do this using Array#sort by converting the boolean values of state:

Number(true) //1
Number(false) //0

const dic = [
  { state: false, id: 1 },
  { state: true, id: 2 },
  { state: false, id: 3 },
  { state: true, id: 4 },
  { state: false, id: 5 }
];

dic.sort(({ state: stateA = false }, { state: stateB = false }) =>
  Number(stateB) - Number(stateA)
);

console.log(dic);
like image 199
Majed Badawi Avatar answered Sep 22 '25 00:09

Majed Badawi


You can complete it by doing simplify like this.

dic.sort((a, b) => b.state - a.state);

Explain:

We all know that:

false // 0
true // 1

So

false - true // -1
true - false // 1
true - true // 0
false - false // 0

Demo

const dic = [
  { state: false, id: 1 },
  { state: true, id: 2 },
  { state: false, id: 3 },
  { state: true, id: 4 },
  { state: false, id: 5 }
];

dic.sort((a, b) => b.state - a.state);

console.log(dic);
like image 34
Nguyễn Văn Phong Avatar answered Sep 22 '25 01:09

Nguyễn Văn Phong