Array
sort

📊 Sorts an array of elements in ascending or descending order.

Immutable: This function does not mutate the original array.

The following types are supported:

  • Number
  • String
  • Boolean
  • Date
⚠️

Mixed-type arrays cannot be sorted correctly.

Syntax

import { sort } from '@opentf/std';
 
sort<T>(arr: T[] = [], order: 'asc' | 'desc' = 'asc'): T[]

Parameters

  • arr: The source array to sort.
  • order: The sort order. Can be 'asc' (ascending) or 'desc' (descending). Defaults to 'asc'.

Returns

A new sorted array.

Examples

sort([1, 3, 2]) //=> [1, 2, 3]
 
sort(['x', 'z', 'y'], 'desc') //=> ['z', 'y', 'x']
 
const dates = [new Date(2023, 0, 1), new Date(2022, 0, 1)];
sort(dates) //=> [2022-01-01, 2023-01-01]

Related

Try