How to use a Custom Comparator Function for Objects In Javascript

When dealing with objects that have a Boolean property, a custom comparator function can be used to sort the array based on the Boolean property.

Example: This example demonstrates sorting an array of objects based on a Boolean property.

JavaScript
let arr = [
    { name: "Alice", active: false },
    { name: "Bob", active: true },
    { name: "Charlie", active: false },
    { name: "David", active: true },
    { name: "Eve", active: false }
];

function sortObjectsByBoolean(arr) {
    arr.sort((a, b) => b.active - a.active);
}

sortObjectsByBoolean(arr);

console.log(arr);

Output
[
  { name: 'Bob', active: true },
  { name: 'David', active: true },
  { name: 'Alice', active: false },
  { name: 'Charlie', active: false },
  { name: 'Eve', active: false }
]


Sort an array of objects using Boolean property in JavaScript

Given the JavaScript array containing Boolean values. The task is to sort the array on the basis of Boolean value with the help of JavaScript. There are two approaches that are discussed below:

Table of Content

  • Using Array.sort() Method and === Operator
  • Using Array.sort() and reverse() Methods
  • Using a Custom Comparator Function for Objects

Similar Reads

Using Array.sort() Method and === Operator

Use JavaScript Array.sort() method.In the Comparison condition, Use === operator to compare the Boolean objects.Return 0, 1, and -1 means equal, greater, and smaller respectively depending upon the comparison....

Using Array.sort() and reverse() Methods

Use JavaScript Array.sort() method.In Comparison condition, Subtract the first element from the second one to compare the objects and return that value.Use .reverse() method, If the result is needed to be reversed....

Using a Custom Comparator Function for Objects

When dealing with objects that have a Boolean property, a custom comparator function can be used to sort the array based on the Boolean property....

Contact Us