Categories
JavaScript Answers

How to do partial sums of array items in JavaScript?

Spread the love

Sometimes, we want to do partial sums of array items in JavaScript.

In this article, we’ll look at how to do partial sums of array items in JavaScript.

How to do partial sums of array items in JavaScript?

To do partial sums of array items in JavaScript, we can use the JavaScript array reduce method.

For instance, we write:

const arr = [0, 1, 2, 3, 4, 5]
const partialSums = arr.reduce((acc, el, i, arr) => {
  const slice = arr.slice(0, i + 1)
  const sum = slice.reduce((a, b) => a + b, 0)
  return [...acc, sum]
}, [])
console.log(partialSums)

We call reduce with a callback that takes the index i and array arr parameters.

Then we take the parts of of arr from index 0 to i with slice.

Next, we compute the partial sum with reduce.

And then we return the acc array spread into the array and the new sum.

Then in the 2nd argument we set the initial partialSums value to an empty array.

Therefore, partialSums is [0, 1, 3, 6, 10, 15].

Conclusion

To do partial sums of array items in JavaScript, we can use the JavaScript array reduce method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *