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

x/earthstar/src/entries/npm.ts>compareArrays

Storage for private, distributed, offline-first applications.
Go to Latest
function compareArrays
Re-export
import { compareArrays } from "https://deno.land/x/earthstar@v10.0.1/src/entries/npm.ts";

example usage: myArrayOfArrays.sort(arrayCompare)

Compare arrays element by element, stopping and returning the first non-EQ comparison. Earlier array items are more important. When arrays are different lengths and share the same prefix, the shorter one is less than the longer one. In other words, the undefined you would get by reading of the end of the array counts as lower than any other value.

For example, this list of arrays is sorted:

  • [1],
  • [1, 1],
  • [1, 1, 99],
  • [1, 2],
  • [1, 2],
  • [2],
  • [2, 99],
  • [2, 99, 1],

sortOrders is an array of 'ASC' | 'DESC' strings. Imagine it's applied to the columns of a spreadsheet.

For example, to sort DESC by the first item, and ASC by the second item: compareArrays(['hello', 123], ['goodbye', 456], ['DESC', 'ASC']).

Sort order defaults to 'ASC' when the sortOrders array is not provided. If the sortOrders array is shorter than the arrays to be sorted, it acts as if it was filled out with additional 'ASC' entries as needed. A sort order of 'DESC' in the appropriate column can make longer arrays come before shorter arrays.

sortOrders ['ASC', 'DESC'] sorts in this order:

  • [1, 99],
  • [1, 2],
  • [1], // shorter array comes last, because of DESC in this column
  • [2], // but first element is still sorted ASC

Parameters

a: T[]
b: T[]
optional
sortOrders: SortOrder[]