38

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]
Mauro74
  • 4,274
  • 13
  • 50
  • 75
  • I posted an answer which gives both highest number as well as all values if highest number is greater then your certain number – shivgre Apr 05 '16 at 10:47

4 Answers4

50

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++);
Mat
  • 2,071
  • 2
  • 23
  • 33
29

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

Littm
  • 4,895
  • 4
  • 28
  • 36
8
var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

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

     arr.push(i);
}
Mihai Iorga
  • 36,863
  • 13
  • 100
  • 102
3

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.

skunkfrukt
  • 1,454
  • 1
  • 12
  • 21