Skip to content

orderSort

Sorts an array arr based on a specified order order.

getter is a function that transforms elements of the array arr to keys that can be used for sorting, which can be a field path of getByPath or a function.

If getter is not provided, the orderSort use the array arr element itself as the sorting key.

Elements not in the order array maintain their original relative order and be placed at the end.

Added in v0.0.3

Usage

ts
import { orderSort } from 'parsnip-kit'

const arr = [{ id: 0 }, { id: 2 }, { id: 1 }, { id: 3 }, { id: 4 }]
const order = [1, 3, 2]
const getter = (item: { id: number }) => item.id

const sortedArr = orderSort(arr, order, getter)
// [{ id: 1 }, { id: 3 }, { id: 2 }, { id: 0 }, { id: 4 }]

API

Type Parameter

ArgTypeDescription
TType of elements of array to sort

Arguments

ArgTypeOptionalDefaultDescription
arrT[]falseundefinedThe array to be sorted
orderany[]falseundefinedThe array specifying the desired order
getterstring | ((item: T) => any)trueundefinedTransform the elements of the array into keys that can be used for sorting

Returns

Type
T[]