UNPKG

diginext-utils

Version:
24 lines 738 B
import { sum } from "./sum.js"; /** * Calculates the average (mean) of all elements in an array. * If a key is provided, averages the values of that property from each object. * * @template T - The type of elements in the array * @param array - The array to average * @param key - Optional key to average values from objects * @returns The average of all values, or 0 if array is empty * * @example * ```ts * average([1, 2, 3, 4]); // 2.5 * average([{ score: 80 }, { score: 90 }], 'score'); // 85 * average([]); // 0 * ``` */ export function average(array, key) { if (!Array.isArray(array) || array.length === 0) { return 0; } return sum(array, key) / array.length; } //# sourceMappingURL=average.js.map