diginext-utils
Version:
README.md
27 lines • 846 B
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.average = average;
const sum_1 = require("./sum");
/**
* 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
* ```
*/
function average(array, key) {
if (!Array.isArray(array) || array.length === 0) {
return 0;
}
return (0, sum_1.sum)(array, key) / array.length;
}
//# sourceMappingURL=average.js.map