Files
30-seconds-of-code/snippets/accumulate.md
Isabelle Viktoria Maciohsek a2dc83e9a9 Update accumulate
2020-10-18 20:00:18 +03:00

556 B

title, tags
title tags
accumulate math,array,intermediate

Creates an array of partial sums.

  • Use Array.prototype.reduce(), initialized with an empty array accumulator to iterate over nums.
  • Use Array.prototype.slice(-1), the spread operator (...) and the unary + operator to add each value to the accumulator array containing the previous sums.
const accumulate = (...nums) => nums.reduce((acc, n) => [...acc, n + +acc.slice(-1)],[]);
accumulate(1, 2, 3, 4); // [1, 3, 6, 10]
accumulate(...[1, 2, 3, 4]); // [1, 3, 6, 10]