CKTIS / JavaScript
Array reductions and statistics
A reduction combines array elements into one result. Learn how the Array.prototype.reduce() accumulator supports counts, sums, minima, maxima, and means, including explicit handling of empty and sparse arrays.
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
array.reduce((accumulator, currentValue, currentIndex, array) => nextAccumulator, initialValue)A reduction turns a sequence of values into one result, such as a sum or a statistics object. Array.prototype.reduce() visits existing elements in ascending index order. Its callback receives the accumulator, current value, index, and array; its return value becomes the next accumulator. Return it on every call.
Supply initialValue to make the starting state explicit. Without it, the first existing element becomes the accumulator and processing starts with the next one. An empty array without initialValue throws TypeError; with it, the initial value is returned. Holes without an inherited indexed property are skipped, so array.length is not necessarily the number of processed values.
The example computes count, sum, min, and max in one pass, then calculates the mean as sum / count. Infinity and -Infinity seed the extrema. For empty input, the result uses null for the minimum, maximum, and mean—an explicit convention of this example. The callback mutates only the fresh accumulator object; reduce() itself does not mutate the array.
The example assumes finite Number values. Establish validation rules for external data: + can concatenate strings, and NaN disrupts calculations. Number arithmetic can introduce rounding errors. The reduction and serialization with JSON.stringify() use ECMAScript features. Displaying the result, however, requires console.log(), which is part of a Web API in browsers and is provided by the host in Node.js. Check that console.log() is available in your execution environment.
Examples
const values = [4, 8, 6, 2];
const stats = values.reduce((acc, value) => {
acc.count += 1;
acc.sum += value;
acc.min = Math.min(acc.min, value);
acc.max = Math.max(acc.max, value);
return acc;
}, { count: 0, sum: 0, min: Infinity, max: -Infinity });
const mean = stats.count === 0 ? null : stats.sum / stats.count;
const min = stats.count === 0 ? null : stats.min;
const max = stats.count === 0 ? null : stats.max;
console.log(JSON.stringify({ ...stats, min, max, mean }));Result
{"count":4,"sum":20,"min":2,"max":8,"mean":5}The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.