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]
CodePudding user response:
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);
CodePudding user response:
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)
CodePudding user response:
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?