Sort a Boolean Array in JavaScript, TypeScript, or Node.js

Sorting arrays in a common use case in application development. Sorting arrays by a boolean value is not as typical as sorting by numbers or strings. At least for us at Future Studio.

This tutorial shows you how to sort a JavaScript boolean array. Also: this approach works in TypeScript, too!

Node.js Series Overview

  1. How to Check if an Object is Empty in JavaScript or Node.js (Coming soon)

Sort a Boolean Array in JavaScript or TypeScript

The .sort() method in JavaScript or Typescript accepts a comparator function providing you two values of the array.

When sorting booleans, you can short-circuit the comparator and only use a single value. The single boolean value is enough to check whether it’s “true” or “false” and return 1 (value comes first) or -1 (value comes last):

[true, false, true, false].sort(value => {
  return value ? 1 : -1 // `false` values first
})

// [ false, false, true, true ]

Depending on your sort direction, you may want the true values first. Switch the return values in the comparator and return -1 if you want all “true” value to come first:

[true, false, true, false].sort(value => {
  return value ? -1 : 1 // `true` values first
})

// [ false, false, true, true ]

This Code Snippet Works in TypeScript

TypeScript requires you to run arithmetic operations on one of these types: any, number, bigint, or enum. The TypeScript linter fails when sorting a boolean array using a - b (a minus b).

Checking whether the given value is true and returning a number works fine in TypeScript. Sweet!

Explore the Library

Find interesting tutorials and solutions for your problems.