How to Make an Array from Range in JavaScript
One of the easiest and cleanest ways is to use a combination of fill()
and map()
:
Array(toValue + 1).fill(fromValue).map((x, y) => x + y);
Example:
<script>
var fromValue = 3;
var howMany = 8;
var myArray = Array(howMany).fill(fromValue).map((x, y) => x + y);
console.log(myArray);
</script>
Output (console):
(8) [3, 4, 5, 6, 7, 8, 9, 10]
Ready-to-use function:
<script>
function arrayFromRange(fromValue, howMany) {
return Array(howMany).fill(fromValue).map((x, y) => x + y);
}
console.log( arrayFromRange(10, 11) ); // Output (console): (11) [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
</script>