Mauro74
Mauro74

Reputation: 4826

javascript create array from for loop

I have a years range stored into two variables. I want to create an array of the years in the range.

something like:

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

for (var i = yearStart; i < yearEnd; i++) {

     var obj = {
        ... 
     };

      arr.push(obj);
}

What should I put inside the obj ?

The array I'd like to generate would be like:

arr = [2000, 2001, 2003, ... 2039, 2040]

Upvotes: 48

Views: 215957

Answers (4)

Mat
Mat

Reputation: 2428

even shorter if you can lose the yearStart value:

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

while(yearStart < yearEnd+1){
  arr.push(yearStart++);
}

UPDATE: If you can use the ES6 syntax you can do it the way proposed here:

let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
    .fill()
    .map(() => yearStart++);

Upvotes: 69

skunkfrukt
skunkfrukt

Reputation: 1570

Remove obj and just do this inside your for loop:

arr.push(i);

Also, the i < yearEnd condition will not include the final year, so change it to i <= yearEnd.

Upvotes: 4

Mihai Iorga
Mihai Iorga

Reputation: 39704

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

for (var i = yearStart; i <= yearEnd; i++) {

     arr.push(i);
}

Upvotes: 10

Littm
Littm

Reputation: 4947

You need to push i

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

for (var i = yearStart; i < yearEnd+1; i++) {
    arr.push(i);
}

Then, your resulting array will be:

arr = [2000, 2001, 2003, ... 2039, 2040]

Hope this helps

Upvotes: 34

Related Questions