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 next

import { createSortByBooleanFn } from '@helpers4/array';
createSortByBooleanFn<T extends Record<string, unknown>>(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