Skip to content

lexSort

Sorts parameter arr lexicographically based on the order specified by parameter order with the default of 'asc'.

The parameter order can be specified as either 'asc' (ascending order) or 'desc' (descending order).

It will call stringComparatorAsc or stringComparatorDesc internally.

The optional parameter getter is used to obtain the string value from elements of arr, with the default being to use the element itself for sorting.

getter can be a field path of getByPath or a callback function.

Added in v0.0.2

Usage

ts
import { lexSort } from 'parsnip-kit'

const fruits = ['banana', 'apple', 'cherry', 'date']
lexSort(fruit)
// ['apple', 'banana', 'cherry', 'date']

const people = [
  { name: 'John', age: 30 },
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 35 }
]

lexSort([...people], 'desc', 'name')
// [
//   { name: 'John', age: 30 },
//   { name: 'Bob', age: 35 },
//   { name: 'Alice', age: 25 }
// ]

lexSort([...people], 'asc', item => item.name)
// [
//   { name: 'John', age: 30 },
//   { name: 'Bob', age: 35 },
//   { name: 'Alice', age: 25 }
// ]

API

Type Parameter

ArgTypeDescription
TType of elements of array
Rextends 'asc' | 'desc' = 'asc' | 'desc'Type of order for sorting

Arguments

ArgTypeOptionalDefaultDescription
arrT[]falseundefinedArray to be sorted
orderRfalseundefinedOrder for sorting
getterstring | ((item: T) => string)falseundefinedFor extracting string values from array elements

Returns

Type
T[]