Partial sum array

JavaScript, Math · Jan 30, 2022

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]

Written by Angelos Chalaris

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub.

More like this

  • Mapped array sum

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

    JavaScript, Math · Nov 3, 2020

  • Cross product of arrays

    Creates a new array out of the two supplied by creating each possible pair from the arrays.

    JavaScript, Math · Oct 22, 2020

  • Array sum

    Calculates the sum of two or more numbers/arrays.

    JavaScript, Math · Oct 22, 2020