averageBy
Calculates the average of an array based on a selector function.
1/**
2 * Calculates the average of an array based on a selector function.
3 *
4 * @param arr - Array of items.
5 * @param fn - Function that returns a number from each item.
6 * @returns The average value, or 0 if array is empty.
7 */
8export function averageBy<T>(arr: T[], fn: (item: T) => number): number {
9 if (arr.length === 0) return 0;
10 return arr.reduce((sum, item) => sum + fn(item), 0) / arr.length;
11}
Flexible Selector Function
Accepts a callback to determine how numerical values are extracted, making it adaptable to various data structures.
Type-Safe and Generic
Uses TypeScript generics to ensure type safety across different array item types.
Handles Empty Arrays Gracefully
Returns
0
instead ofNaN
or throwing an error when the array is empty, promoting safer usage.Concise and Readable
The implementation is straightforward and easy to understand, making it maintainable and less error-prone.
Tests | Examples
1test('averageBy - objects with numeric field', () => {
2 const data = [{ score: 10 }, { score: 20 }, { score: 30 }];
3 expect(averageBy(data, item => item.score)).toBe(20);
4});
5
6test('averageBy - empty array returns 0', () => {
7 expect(averageBy([], item => 1)).toBe(0);
8});
9
10test('averageBy - constant selector', () => {
11 expect(averageBy(['a', 'b', 'c'], () => 2)).toBe(2);
12});
13
14test('averageBy - computed values', () => {
15 const data = [1, 2, 3, 4];
16 expect(averageBy(data, x => x * 2)).toBe(5);
17});
Common Use Cases
Calculating Average Scores or Ratings
Compute average review ratings, test scores, or other metrics from structured data.
Statistical Aggregation
Useful in analytics dashboards or reporting tools to extract and average values from complex datasets.
Financial Calculations
Average prices, transaction values, or earnings across objects representing financial data.
Data Normalization or Transformation
Serve as part of a data pipeline to normalize datasets before further processing.
UI Summaries and Visualizations
Generate averages for summary widgets, charts, or progress bars based on dynamic data.