Reputation: 3185
How can I get values from one number to second number with equally incrementing values, if I supply iteration number? Result should include both start and end values.
Here is example of hardcoded solution
var first = 1;
var second = 1.4;
var times = 5;
var result = [1, 1.1, 1.2, 1.3, 1.4];
How would I get similar result with these values?
first = 1;
second = 1.66;
times = 5;
result = [1, ?, ?, ?, 1.66]
Or this
first = 1;
second = 1.66;
times = 8;
result = [1, ?, ?, ?, ?, ?, ?, 1.66]
Here is Codepen I have tried if it is of any use
Upvotes: 0
Views: 886
Reputation: 138267
result = Array.from({ length: times }, (_, i) => first + (second - first) * i / (times - 1));
You could create an array containing times
elements, and then set each slot to a value between first
and second
. For that a number between 0 and 1 is generated for all slots and then the formula does:
// example for 2 times
first + (second - first) * 0 // = first
first + (second - first) * 1 // = second
Upvotes: 2