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); // 5Related Functions
add
Adds two numbers.
ceil
Computes number rounded up to precision.
divide
Divide two numbers.
floor
Computes number rounded down to precision.
max
Computes the maximum value of array.
maxBy
This method is like max except that it accepts iteratee which is invoked for each element in array to generate the criterion by which the value is ranked.