How to use Array.sort() Method and === Operator In Javascript
- 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.
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]
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
Contact Us