How to Sort Object Array by Boolean Property in JavaScript

Sorting an object array by a boolean property in JavaScript can be efficiently accomplished by leveraging the sort() method. This guide will demonstrate the process using clean, idiomatic examples suitable for any level of engineering expertise.

Understanding the sort method

JavaScript arrays have a built-in sort() method that allows for custom sorting logic via a comparator function. When sorting by a boolean property, this function can simply return the difference between the boolean values of two objects.

Sample object array

Consider an array of objects where each object has a boolean property named isActive.

let users = [ { name: 'Alice', isActive: false }, { name: 'Bob', isActive: true }, { name: 'Charlie', isActive: true }, { name: 'Dave', isActive: false } ];

Sorting the array

To sort by the isActive property:

users.sort((a, b) => a.isActive - b.isActive);

This will sort the array with false values first. To sort with true values first, reverse the operands:

users.sort((b, a) => a.isActive - b.isActive);

Under the hood

The comparator function works by returning:

  • A negative number if the first argument should come before the second.
  • A positive number if the first argument should come after the second.
  • Zero if they are considered equal.

Since false is coerced to 0 and true to 1 during subtraction, this results in the correct sorting order.

Advanced sorting

For a more explicit approach, especially when dealing with TypeScript or to make the code more readable, you can use a comparison that doesn't rely on coercion:

users.sort((a, b) => { return (a.isActive === b.isActive) ? 0 : a.isActive ? -1 : 1; });

Working with TypeScript

In TypeScript, type safety adds robustness to the sorting function:

interface User { name: string; isActive: boolean; } let users: User[] = [ // ...users ]; users.sort((a, b) => Number(b.isActive) - Number(a.isActive));

This ensures that the properties exist and are of the correct type before the sort operation.

Invite only

We're building the next generation of data visualization.