Today I took a break from working with JS objects, and did a challenge involving an array instead.
/* Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]).
Return the running sum of nums.
Example:
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].
*/
Write the function that sums together array items
const runningSum = (array) => {
//loop through the array for the length of the array.
// sum together the previous item from the array to the current item of the array
//return the new array
};
The start seems really easy, just apply a for loop to the array and the deed is done. Not so fast.
for(let i = 0; i<array.length; i++){
}
When working with arrays, I usually start the index (i
) at the value of 0
. Let's think about how this would work in this example.
We need to put together the previous array item [i-1]
and the current array item [i]
. If we run the code as is, with let i = 0
, then the beginning index is -1. That won't do. Javascript arrays are zero indexed and I needed to modify the value of i
, so that [i-1]
returns zero on the first loop. I just decided on changing the value to 1
and that solved the problem.
const runningSum = (array) => {
for(let i = 1; i<array.length; i++){
}
};
After that it is just as easy as suming both values together, set the new value of the existing array to the said sum / new value and continue doing so until the end of the array. After that the new array is returned and that is it.
const runningSum = (array) => {
for (let i = 1; i < array.length; i++) {
let newValue = array[i - 1] + array[i];
array[i] = newValue;
}
return array;
};
I tried the code on a few different examples and got the wanted results. It looks like the code is working as intended.
console.log(runningSum([1, 2, 3, 4]));
console.log(runningSum([1, 1, 1, 1, 1, 1]));
console.log(runningSum([1, 2, 3, 4, 5, 6]));
console.log(runningSum([1, 2, 3, 3, 2, 1]));
/* Results:
[ 1, 3, 6, 10 ]
[ 1, 2, 3, 4, 5, 6 ]
[ 1, 3, 6, 10, 15, 21 ]
[ 1, 3, 6, 9, 11, 12 ]
*/
Conclusion
That is it for today's challenge. It was nice short and simple, great for practicing things that I studied.
Top comments (0)