Files
30-seconds-of-code/snippets/js/s/partial-sum-array.md
Angelos Chalaris 9d032ce05e Rename js snippets
2023-05-19 20:23:47 +03:00

736 B

title, type, language, tags, author, cover, dateModified
title type language tags author cover dateModified
Partial sum array snippet javascript
math
chalarangelo people-on-beach 2022-01-30T13:10:13+02:00

Creates an array of partial sums.

  • Use Array.prototype.reduce(), initialized with an empty array accumulator to iterate over nums.
  • Use Array.prototype.slice() to get the previous partial sum or 0 and add the current element to it.
  • Use the spread operator (...) to add the new partial sum to the accumulator array containing the previous sums.
const accumulate = (...nums) =>
  nums.reduce((acc, n) => [...acc, n + (acc.slice(-1)[0] || 0)], []);
accumulate(1, 2, 3, 4); // [1, 3, 6, 10]
accumulate(...[1, 2, 3, 4]); // [1, 3, 6, 10]