0

I am working on a running sum problem and I keep getting an array of undefined for my output. Here is the example of what the output should be like

Example 1:

Input: nums = [1,2,3,4]
Output: [1,3,6,10]
Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].

here is the work I have so far:

var runningSum = function(arr) {
    const sum = arr.map(n => {
        for (let i = 0; i < arr.length; i++) {
            if (i === 0) {
                n + 0
            } else {
                n + arr[i - 1]
            }
        }
    })
    return sum
};
const arr = [1, 2, 5, 4]
runningSum(arr)
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
Kazim Shabbir
  • 145
  • 1
  • 12

1 Answers1

0

You are missing these 2:

  • index of the current iterated element, I store as nIndex
  • temporary variable that store accumulated sum from beginning to that element, I store as temp

Below fix could help you

var runningSum = function(arr) {
  const sum = arr.map((n, nIndex) => {
    let temp = n
    for (let i = 0; i < nIndex + 1; i++) {
      if (i === 0) {
        temp += 0
      } else {
        temp += arr[i - 1]
      }
    }
    return temp
  })

  return sum
}
const arr = [1, 2, 3, 4]
console.log(runningSum(arr))
hgb123
  • 13,869
  • 3
  • 20
  • 38