← Back to1 LOC

# Create an array of cumulative sum

Written byPhuoc Nguyen
Created
19 Apr, 2020
Last updated
13 Oct, 2021
Category
Array
JavaScript version
accumulate.js
``const accumulate = (arr) =>    arr.map(        (            (sum) => (value) =>                (sum += value)        )(0)    );// Orconst accumulate = (arr) => arr.reduce((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), [0]);``
TypeScript version
accumulate.ts
``const accumulate = (arr: number[]): number[] =>    arr.map(        (            (sum) => (value: number) =>                (sum += value)        )(0)    );// Orconst accumulate = (arr: number[]): number[] => arr.reduce((a, b, i) => (i === 0 ? [b] : [...a, b + a[i - 1]]), [0]);``
Example
example.js
``accumulate([1, 2, 3, 4]); // [1, 3, 6, 10]// 1             = 1// 1 + 2         = 3// 1 + 2 + 3     = 6// 1 + 2 + 3 + 4 = 10``
If you found this post helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks 😍. Your support would mean a lot to me!

## Questions? 🙋

Do you have any questions about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.