I have data like this
let number = 1000
let array = [1,2,3,4,5]
let percentage = 5%
and the output I expected is
array1 = 1000 5%
array2 = 1000 5% 5%
array3 = 1000 5% 5% 5%
array4 = 1000 5% 5% 5% 5%
array5 = 1000 5% 5% 5% 5% 5%
I'm trying add more percentage as the index, I have tried with for loop, but none is working.
can anyone help me with the logic ?
any help is appreciated. Thank you
CodePudding user response:
I tried to understand what you want, but I'm not sure what that is. This code will create a new array where the elements are sum up by the 5% of the previews number.
let array = [1,2,3,4,5]
let percentage = 0.05 // 5%
let newArr = [1000]
array.forEach((element, i) => {
if(i > 0){
newArr.push(newArr[i-1] newArr[i-1] * percentage)
}
})
console.log(newArr)
CodePudding user response:
If the numbers in array is irrelevant, so this may be enough. This will generate a new array with percentage base on index
let number = 1000
let array = [1, 2, 3, 4, 5]
let percentage = 5
const foo = array.reduce((acc, el, index) => {
let result = number
for (let i = 0; i < index 1; i ) {
result = (result / 100) * percentage result
}
acc.push(Math.floor(result))
return acc
}, [])
console.log(foo)