HomeLanguagesJavascriptSort an array of objects using Boolean property in JavaScript

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

  • 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.

Example: This example implements the above approach. 

Javascript




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

  • 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.

Example: This example implements the above approach. 

Javascript




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]
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32706 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7078 POSTS0 COMMENTS
Nicole Veronica
12214 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12303 POSTS0 COMMENTS
Shaida Kate Naidoo
7200 POSTS0 COMMENTS
Ted Musemwa
7457 POSTS0 COMMENTS
Thapelo Manthata
7175 POSTS0 COMMENTS
Umr Jansen
7164 POSTS0 COMMENTS