@trashpanda001/helpers
    Preparing search index...

    Function sortBy

    • A stable array sort using a mapping function.

      This implements the Lisp decorate-sort-undecorate pattern (aka Schwartzian transform): it first maps all the elements, then sorts by the mapped value, and then returns an array of the original elements. If two elements map to the same value, the original element order is preserved.

      Type Parameters

      • T
      • V

      Parameters

      • array: readonly T[]

        the array to sort

      • mapFn: (x: T) => V

        a function that maps each element to a value

      • compareFn: (a: V, b: V) => number

        a function that compares two mapped values

      Returns T[]

      a new sorted array

      Sort by absolute value ascending.

      import { sortBy } from "@trashpanda001/helpers/array"

      sortBy([-3, -1, 2], (x) => Math.abs(x), (a, b) => a - b)
      // [-1, 2, -3]