Array
sortBy

Sorts a list of objects and returns a new array.

Immutable: This does not mutate the given array.

Related:

Syntax

sortBy<T>(
  arr: T[],
  ...tuples: [key: string | ((obj: T) => unknown), order: "asc" | "desc"][]
): T[]

The key in the tuple array must one of object first level props.

Usage

import { sortBy } from "@opentf/std";
 
sortBy([{...}], ['key', 'asc'], [o => o.prop, 'desc']);

Examples

const fruits = [
  { name: 'banana', amount: 2 },
  { name: 'apple', amount: 4 },
  { name: 'pineapple', amount: 2 },
  { name: 'mango', amount: 1 },
  { name: 'orange', amount: 5 },
];
 
sortBy(fruits, ['name', 'asc']);
sortBy(fruits, [(o) => o.name, 'asc']);
//=> [
//   { name: 'apple', amount: 4 },
//   { name: 'banana', amount: 2 },
//   { name: 'mango', amount: 1 },
//   { name: 'orange', amount: 5 },
//   { name: 'pineapple', amount: 2 },
// ]
 
sortBy(fruits, ['amount', 'desc'], ['name', 'asc']);
sortBy(fruits, [o => o.amount, 'desc'], [o => o.name, 'asc']);
//=> [
//  { name: 'orange', amount: 5 },
//  { name: 'apple', amount: 4 },
//  { name: 'banana', amount: 2 },
//  { name: 'pineapple', amount: 2 },
//  { name: 'mango', amount: 1 }
// ]

Try