Skip to content

createSortByBooleanFn

Creates a sort function for objects by a boolean property.

Values are coerced with Boolean() before comparing, so null, undefined, 0, and '' behave as false, and any other truthy value behaves as true.

Available since v3.0.0

import { createSortByBooleanFn } from '@helpers4/array';
// or, from the all-in-one package (same code, one install):
import { createSortByBooleanFn } from 'helpers4/array';
createSortByBooleanFn<T extends object>(property: keyof T, trueFirst: boolean): SortFn<T>
ParameterTypeDescription
propertykeyof TThe property to sort by.
trueFirstbooleanWhether `true` values sort before `false` values (default: `true`).

SortFn<T> — Sort function

Default items float to the top of the list.

const items = [{ isDefault: false }, { isDefault: true }, { isDefault: false }];
items.sort(createSortByBooleanFn('isDefault'))
// => [{ isDefault: true }, { isDefault: false }, { isDefault: false }]

Pass trueFirst = false to invert the priority.

const items = [{ archived: true }, { archived: false }];
items.sort(createSortByBooleanFn('archived', false))
// => [{ archived: false }, { archived: true }]

Sort function type for arrays

type SortFn<T> = (a: T, b: T) => number

View source on GitHub