Code Snippets
/

Numeric Aggregations: Sum, Filter, Closest Pair

Numeric Aggregations: Sum, Filter, Closest Pair

Three numeric questions you will hit again and again on real arrays: sum (with safety against non-number inputs), summary statistics (sum, average, min, max in one pass), and the smallest absolute difference between any two numbers. Each one is short, but the right answer changes with the input shape: mixed-type arrays, large arrays, and "closest pair" all reward different idioms.

JavaScript
Medium
3 snippets
arrays
map-filter-reduce
math

1,071 views

6

// Plain sum: trusts that every item is a finite number.
const sum = (arr) => arr.reduce((acc, n) => acc + n, 0);
console.log(sum([1, 2, 3, 4, 5])); // 15

// Coerced + filtered: ignore strings, undefined, null, NaN, Infinity.
const sumNumeric = (arr) =>
    arr.reduce((acc, x) => acc + (Number.isFinite(x) ? x : 0), 0);

console.log(sumNumeric([1, 'two', 3, null, 5, NaN, 7])); // 16
console.log(sumNumeric([10, '20', 30]));                 // 40 (string '20' rejected)

// If you DO want to coerce numeric strings, parse first.
const sumLoose = (arr) =>
    arr.reduce((acc, x) => {
        const n = Number(x);
        return acc + (Number.isFinite(n) ? n : 0);
    }, 0);

console.log(sumLoose([10, '20', 30, 'x'])); // 60

reduce((acc, n) => acc + n, 0) is the textbook sum and is correct as long as the input is well-typed. In real data (CSV imports, JSON from a third party), you often get strings, null, or NaN mixed in, and the plain sum returns NaN from then on. Number.isFinite(x) rejects those without coercing strings, so the safe form picks up only real finite numbers. Choose between strict (reject strings outright) and loose (parse strings via Number(x)) based on whether numeric strings are a valid input in your data contract; do not silently accept either form when you have not decided.