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.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more