EN
JavaScript - create array from for loop
1 answers
0 points
I have a range stored into two variables and I want to create an array within the range.
Something like this:
xxxxxxxxxx
1
const start = 10;
2
const end = 20;
3
4
const array = [];
5
6
for (let i = start; i < end; i++) {
7
8
const object = {
9
// ...
10
};
11
12
array.push(object);
13
}
What should I put inside the object to make it work?
The result I'd like to get would be:
xxxxxxxxxx
1
array = [10, 11, 12, , 20]
1 answer
0 points
ES6+ solution
You can use Array()
constructor to create array, then fill()
and map()
methods to fill the array with the values in range:
xxxxxxxxxx
1
let start = 10;
2
let end = 20;
3
4
const years = Array(end - start + 1)
5
.fill()
6
.map(() => start++);
7
8
console.log(years);
Solution for older versions
This solution uses a simple while
loop to push
values in range inside the array
.
xxxxxxxxxx
1
var start = 10;
2
var end = 20;
3
4
var array = [];
5
6
while (start < end + 1) {
7
array.push(start++);
8
}
9
10
console.log(array);
References
0 commentsShow commentsAdd comment