48

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]
asked Sep 19, 2012 at 8:35
1
  • I posted an answer which gives both highest number as well as all values if highest number is greater then your certain number Commented Apr 5, 2016 at 10:47

5 Answers 5

69

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++);
answered Sep 19, 2012 at 8:59
Sign up to request clarification or add additional context in comments.

Comments

34

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

answered Sep 19, 2012 at 8:36

Comments

10
var yearStart = 2000;
var yearEnd = 2040;
var arr = [];
for (var i = yearStart; i <= yearEnd; i++) {
 arr.push(i);
}
answered Sep 19, 2012 at 8:37

Comments

4

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.

answered Sep 19, 2012 at 8:38

Comments

0

If you like generators, then this might be a more elegant approach:

function* range(start, stop) {
 for (let i = start; i < stop; i++) yield i;
}
const years = range(2000, 2040).toArray();
console.log(years);

answered Feb 23 at 7:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.