Back to Functions

meanBy

math

This method is like mean except that it accepts iteratee which is invoked for each element in array to generate the value to be averaged.

Installation

Import
import { meanBy } from '@tulx/utils';

Source Code

Implementation
/**
 * This method is like mean except that it accepts iteratee which is invoked for each element in array to generate the value to be averaged.
 *
 * @param array - The array to iterate over.
 * @param iteratee - The iteratee invoked per element.
 * @returns Returns the mean.
 *
 * @example
 * ```ts
 * const objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
 * meanBy(objects, (o) => o.n); // 5
 * ```
 */
export function meanBy<T>(
  array: readonly T[],
  iteratee: ((value: T) => number) | string
): number {
  if (array.length === 0) {
    return NaN;
  }

  const getValue =
    typeof iteratee === 'string'
      ? (item: T) => (item as Record<string, number>)[iteratee]
      : iteratee;

  const sum = array.reduce((acc, val) => acc + getValue(val), 0);
  return sum / array.length;
}

Example

import { meanBy } from '@tulx/utils';

const objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
meanBy(objects, (o) => o.n); // 5

Related Functions