You can sort an array of objects according to their boolean properties by the .sort() method. Here’s an example of how you can sort an array of objects with a boolean property:
const users = [
{
name: "John",
isVerified: false,
},
{
name: "Kim",
isVerified: true,
},
{
name: "Mehdi",
isVerified: false,
},
]
users.sort((a,b) =>{
if(a.isVerified && !b.isVerified) {
return -1;
}else if (!a.isVerified && b.isVerified){
return 1;
}else {
return 0
}
})
console.log(users);
// [
{ name: "Kim", isVerified: true },
{ name: "John", isVerified: false },
{ name: "Mehdi", isVerified: false }
]
In the .sort() method if the comparator function returns a value less than 0, it means that a should come before b in the sorted array. If it returns a value greater than 0, it means that b should come before a. If it returns 0, it means that the relative order of a and b doesn’t matter.
Top comments (0)