I have a known startValue
, a known finalValue
and a fixed number of allowed iterations
.
Starting with startValue
I need to keep increasing the value each time round the loop until I reach finalValue
.
I want the increase to be proportional (gradual).
I'm trying the below and the numbers seem to make sense except for the jump at the start and end of the array.
There seems to be a big jump from the 1st value to the 2nd and another big jump from the one before last to the last one.
The values in between seem to be increasing gradually though.
Is this the correct or best approach?
let startValue = 0.07
let finalValue = 4.76
let iterations = 10
let values = [startValue]
iterations--
while (iterations) {
let [previousValue] = values.slice(-1)
let nextValue = (finalValue - previousValue) / iterations
values.push(nextValue)
iterations--
}
values.push(finalValue)
document.getElementById('values').innerHTML = `[<br> ${values.join(',<br/> ')}<br>]`
<div id="values"></div>
CodePudding user response:
You can generate an array based on the following logic:
1st item: startValue
2nd item: startValue diff
3rd item: startValue (diff * 2)
and so on...
const
startValue = 0.07,
finalValue = 4.76,
iterations = 10,
diff = (finalValue - startValue) / iterations,
values = Array.from(
{ length: iterations 1 },
(_, i) => startValue i * diff
);
console.log(values);