Open In App

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:

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

Example: This example implements the above approach. 






let arr = [false, true, false, true, false];
 
function GFG_Fun() {
    arr.sort(function (x, y) {
        return (x === y) ? 0 : x ? -1 : 1;
    });
 
    console.log("Sorted Array - [" + arr + "]");
}
 
GFG_Fun();

Output
Sorted Array - [true,true,false,false,false]

Method 2: Using Array.sort() and reverse() Methods

Example: This example implements the above approach. 






let arr = [false, true, false, true, false];
 
function GFG_Fun() {
    arr.sort((a, b) => b - a).reverse();
 
    console.log("Sorted Array - [" + arr + "]");
}
 
GFG_Fun();

Output
Sorted Array - [false,false,false,true,true]

Article Tags :