'How to consecutively add values from one array to another and store the value in a new array in javascript?
I have 2 arrays:
const initialAmount = [50]
const transactionAmounts = [ -10, 10, 10, -1, -5, -10, 5, 5, 5, 10, 10, 10, 1, -1, -2, -5, -10 ]
How do i return an array that adds each value from transactionAmounts to the initialAmount? (excluding the first, which should be the initial value)
For example, it should return:
const valueAfterEachTransaction = [50, 40, 50, 60, 59, 54, 44, 49, 54, 59, 69, 79, 89, 90, 89, 87, 82, 72]
Solution 1:[1]
You could take a closure over the sum and get all elememts of both arrays for mapping the acutal sum.
const
initial = [50],
transactions = [-10, 10, 10, -1, -5, -10, 5, 5, 5, 10, 10, 10, 1, -1, -2, -5, -10],
result = [...initial, ...transactions].map((s => v => s += v)(0));
console.log(...result);
Solution 2:[2]
const initialAmount = [50]
const transactionAmounts = [ -10, 10, 10, -1, -5, -10, 5, 5, 5, 10, 10, 10, 1, -1, -2, -5, -10 ]
const newArray = [initialAmount[0]]
let value = initialAmount[0]
let i = 0
do {
value = value + transactionAmounts[i]
newArray[i+1] = value
i++;
}
while (i < transactionAmounts.length);
console.log(newArray)
const initialAmount = [50]
const transactionAmounts = [ -10, 10, 10, -1, -5, -10, 5, 5, 5, 10, 10, 10, 1, -1, -2, -5, -10 ]
const newArray = [initialAmount[0]]
let value = initialAmount[0]
let i = 0
do {
value = value + transactionAmounts[i]
newArray[i+1] = value
i++;
}
while (i < transactionAmounts.length);
console.log(newArray)
Solution 3:[3]
Maybe I'm missing something here, but this seems to be a straightforward map, after you handle the missing initial value.
const combine = ([x], ys) => [0, ...ys] .map (y => x + y)
const initialAmount = [50]
const transactionAmounts = [-10, 10, 10, -1, -5, -10, 5, 5, 5, 10, 10, 10, 1, -1, -2, -5, -10]
console .log (combine (initialAmount, transactionAmounts))
.as-console-wrapper {max-height: 100% !important; top: 0}
I'm curious of what your underlying need is. This seems an odd requirement. Why is the initial value passed in an array? Why is there an implied 0 to add to the first one. Is this an XY problem?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nina Scholz |
| Solution 2 | hamid mehmood |
| Solution 3 | Scott Sauyet |
