JavaScript Snippet

Numeric Aggregations: Sum, Filter, Closest Pair

Difficulty: Medium

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.

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,068 views

6

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.