How to Sort an Array of Objects Using Boolean Properties in JavaScript
Sorting an array of Boolean values or objects with Boolean properties is a common JavaScript operation. This tutorial will cover three approaches with examples, making it easy to understand and implement.
Table of Contents
- Using
Array.sort()
Method and===
Operator - Using
Array.sort()
andreverse()
Methods - Using a Custom Comparator Function for Objects
1. Using Array.sort()
Method and ===
Operator
The Array.sort()
method is a built-in function for sorting arrays. When sorting Boolean values, you can use the strict equality operator (===
) to compare elements.
Steps:
- Use
Array.sort()
to sort the array. - Compare values using
===
. - Return:
-
0
if the values are equal, -
-1
if the first value should come before the second, -
1
if the first value should come after the second.
-
Example:
let arr = [false, true, false, true, false];
function sortBooleanArray() {
arr.sort(function (x, y) {
return (x === y) ? 0 : x ? -1 : 1;
});
console.log("Sorted Array - [" + arr + "]");
}
sortBooleanArray();
Output:
Sorted Array - [true, true, false, false, false]
2. Using Array.sort()
and reverse()
Methods
This approach uses subtraction to compare values, then applies the reverse()
method if needed.
Steps:
- Use
Array.sort()
with a comparison function(a, b) => b - a
. - Reverse the array if you want to switch the order.
Example:
let arr = [false, true, false, true, false];
function sortAndReverse() {
arr.sort((a, b) => b - a).reverse();
console.log("Sorted Array - [" + arr + "]");
}
sortAndReverse();
Output:
Sorted Array - [false, false, false, true, true]
3. Using a Custom Comparator Function for Objects
When sorting objects by a Boolean property, you can create a custom comparator function.
Steps:
- Define a comparator that compares the Boolean properties of the objects.
- Use
Array.sort()
with the comparator.
Example:
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 }
]
When to Use Each Method?
-
Simple Arrays: Use
Array.sort()
with a comparison function. - Objects: Use a custom comparator to sort by specific properties.
-
Reverse Order Needed: Use
reverse()
after sorting.
Bonus Tip:
Sorting large arrays efficiently requires keeping operations lightweight. For objects with multiple criteria, chain comparison logic in the comparator function.
By mastering these approaches, you can confidently sort Boolean values or properties in JavaScript!
Top comments (0)