DEV Community

Cover image for How to sort objects according to True and False values in Javascript
Khwaja Billal Siddiqi
Khwaja Billal Siddiqi

Posted on

How to sort objects according to True and False values in Javascript

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 }
   ]
Enter fullscreen mode Exit fullscreen mode

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)