Average finite values picked by function, path, or key array
A performance dashboard averages metrics from monitoring samples. Samples come from different agents, so some are missing fields, some report null when a probe timed out, and some send numbers as strings. A single bad sample must not turn the whole average into NaN.
Implement averageBy(items, selector). It reads one value from each item with selector and returns the mean of the values that are finite numbers.
averageBy(items, selector) // => number | null
selector(item, index). Its return value is the item’s value.'timing.ttfb'. Each part reads one property.['percentiles', 'p.95'].If a path reaches null or undefined before its last key, the item’s value is undefined. Reading a path never throws.
typeof value === 'number' and Number.isFinite(value) count. Skip everything else: null, undefined, NaN, Infinity, strings such as '120', booleans, and objects.null when no value counts, including for an empty array.items.const samples = [
{ region: 'eu', timing: { ttfb: 120, lcp: 2400 } },
{ region: 'us', timing: { ttfb: 80, lcp: null } },
{ region: 'eu', timing: { ttfb: '95' } },
{ region: 'ap' },
];
averageBy(samples, 'timing.ttfb'); // => 100 ((120 + 80) / 2)
averageBy(samples, 'timing.lcp'); // => 2400
averageBy(samples, 'timing.fid'); // => null
averageBy(samples, (sample) => (sample.region === 'eu' ? sample.timing.ttfb : undefined));
// => 120 (the '95' string is skipped)
averageBy(samples, (_, index) => index * 10); // => 15
averageBy([{ percentiles: { 'p.95': 310 } }, { percentiles: { 'p.95': 290 } }], ['percentiles', 'p.95']);
// => 300
averageBy([], 'x'); // => null