@mirei/ts-collections
    Preparing search index...

    Function median

    • Calculates the median of the numeric values produced by source.

      Type Parameters

      • TElement

        Type of elements within the source iterable.

      Parameters

      • source: Iterable<TElement>

        The source iterable to inspect.

      • Optionalselector: Selector<TElement, number>

        Optional projection that extracts the numeric value for each element. Defaults to treating the element itself as numeric.

      • Optionaltie: MedianTieStrategy

        Determines how the median is resolved when source contains an even number of elements. Defaults to "interpolate", which averages the two central values. Specify "low" or "high" to choose the lower or higher neighbour respectively.

      Returns number

      The calculated median, or NaN when source contains no elements.

      Re-throws any error thrown while iterating source or executing selector.

      source is enumerated once and buffered so a selection algorithm can locate the middle element(s) without fully sorting. Supply selector when elements are not already numeric.

      const medianValue = median([1, 5, 2, 4, 3]);
      console.log(medianValue); // 3

      const people = [
      { name: 'Alice', age: 23 },
      { name: 'Bella', age: 21 },
      { name: 'Mirei', age: 22 },
      { name: 'Hanna', age: 20 },
      { name: 'Noemi', age: 29 }
      ];
      const medianAge = median(people, p => p.age);
      console.log(medianAge); // 22