diff --git a/README.md b/README.md index 8736dbb53..aa9d00130 100644 --- a/README.md +++ b/README.md @@ -6106,6 +6106,7 @@ const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); Examples ```js +sum(1, 2, 3, 4); // 10 sum(...[1, 2, 3, 4]); // 10 ``` diff --git a/docs/math.html b/docs/math.html index d5bb53d27..13b07a22e 100644 --- a/docs/math.html +++ b/docs/math.html @@ -273,7 +273,8 @@ own individual rating by supplying it as the third argument.
standardDeviation([10, 2, 38, 23, 38, 23, 21]); // 13.284434142114991 (sample)
 standardDeviation([10, 2, 38, 23, 38, 23, 21], true); // 12.29899614287479 (population)
 

sum

Returns the sum of two or more numbers/arrays.

Use Array.prototype.reduce() to add each value to an accumulator, initialized with a value of 0.

const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
-
sum(...[1, 2, 3, 4]); // 10
+
sum(1, 2, 3, 4); // 10
+sum(...[1, 2, 3, 4]); // 10
 

sumBy

Returns the sum of an array, after mapping each element to a value using the provided function.

Use Array.prototype.map() to map each element to the value returned by fn, Array.prototype.reduce() to add each value to an accumulator, initialized with a value of 0.

const sumBy = (arr, fn) =>
   arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0);
 
sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 20