Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

std/collections/mod.ts>sortBy

Deno standard library
Go to Latest
The Standard Library has been moved to JSR. See the blog post for details.
function sortBy
import { sortBy } from "https://deno.land/std@0.206.0/collections/mod.ts";

Returns all elements in the given collection, sorted by their result using the given selector. The selector function is called only once for each element. Ascending or descending order can be specified.

Examples

Example 1

import { sortBy } from "https://deno.land/std@0.206.0/collections/sort_by.ts";
import { assertEquals } from "https://deno.land/std@0.206.0/assert/assert_equals.ts";

const people = [
  { name: "Anna", age: 34 },
  { name: "Kim", age: 42 },
  { name: "John", age: 23 },
];
const sortedByAge = sortBy(people, (it) => it.age);

assertEquals(sortedByAge, [
  { name: "John", age: 23 },
  { name: "Anna", age: 34 },
  { name: "Kim", age: 42 },
]);

const sortedByAgeDesc = sortBy(people, (it) => it.age, { order: "desc" });

assertEquals(sortedByAgeDesc, [
  { name: "Kim", age: 42 },
  { name: "Anna", age: 34 },
  { name: "John", age: 23 },
]);

Parameters

array: readonly T[]
selector: (el: T) => number
optional
options: SortByOptions

Parameters

array: readonly T[]
selector: (el: T) => string
optional
options: SortByOptions

Parameters

array: readonly T[]
selector: (el: T) => bigint
optional
options: SortByOptions

Parameters

array: readonly T[]
selector: (el: T) => Date
optional
options: SortByOptions