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

4

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.

Heroku

Deliver your unique apps, your own way.

Heroku tackles the toil — patching and upgrading, 24/7 ops and security, build systems, failovers, and more. Stay focused on building great data-driven applications.

Learn More

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started →

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay