Skip to content
Related Articles
Open in App
Not now

Related Articles

Sort an array of objects using Boolean property in JavaScript

Improve Article
Save Article
  • Last Updated : 24 Jan, 2023
Improve Article
Save Article

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. Here 2 approaches are discussed here. 

Approach 1:

  • Use JavaScript Array.sort() method.
  • In 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 1: This example implements the above approach. 

html




<head>
    <script src=
    </script>
</head>
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <p id="GFG_UP">
    </p>
    <button onclick="GFG_Fun();">
        click here
    </button>
    <p id="GFG_DOWN">
    </p>
    <script>
        var up = document.getElementById('GFG_UP');
        var down = document.getElementById('GFG_DOWN');
        a = [false, true, false, true, false];
        up.innerHTML =
            "Click on the button to sort the array"+
        "on boolean property.<br>Array = [" + a + "]";
          
        function GFG_Fun() {
            a.sort(function(x, y) {
                return (x === y) ? 0 : x ? -1 : 1;
            });
            down.innerHTML = "Sorted Array - [" + a + "]";
        }
    </script>
</body>

Output:

Sort an array of objects using Boolean property in JavaScript

Sort an array of objects using Boolean property in JavaScript

Approach 2: 

  • 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 2: This example implements the above approach. 

html




<head>
    <script src=
    </script>
</head>
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
    <p id="GFG_UP">
    </p>
    <button onclick="GFG_Fun();">
        click here
    </button>
    <p id="GFG_DOWN" style="color: green;">
    </p>
    <script>
        var up = document.getElementById('GFG_UP');
        var down = document.getElementById('GFG_DOWN');
        a = [false, true, false, true, false];
        up.innerHTML =
        "Click on the button to sort the array on boolean "+
        "property.<br>Array = [" + a + "]";
          
        function GFG_Fun() {
            a.sort((a, b) => b - a).reverse();
            down.innerHTML = "Sorted Array - [" + a + "]";
        }
    </script>
</body>

Output:

Sort an array of objects using Boolean property in JavaScript

Sort an array of objects using Boolean property in JavaScript


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!