0
a = (2000..Date.today.year).to_a

In Ruby, above expression returns [2000, 2001, ...snip..., 2018]

I would like to know equivalent JavaScript code.

a = Array.from({length: new Date().getFullYear() - 2000 + 1}, (_, i) => i + 2000)

This can be an answer, but I'm looking for better code in terms of

  • Wider browser support without polyfill than above code
  • Shorter code like specifing start and end as Ruby's one (My JS example is ugly since I wrote 2000 twice).

A code which satisfies either one is helpful.

EDIT

I would like to use value a in Vue.js's v-for loop in inline manner like

<option v-for="year in a" :value="year">FY{{year}}</option>

So single expression is desirable.

yskkin
  • 854
  • 7
  • 24

1 Answers1

1

The simplest (but not shortest) solution would be to use a loop:

a = []; 
for (var year = new Date().getFullYear(); year >= 2000; --year) 
    a.unshift(year);

>>>> [2000, 2001, ..., 2017, 2018]

or perhaps to define a function:

function range(from, to) {
    var res = [];
    for (var i = from; i <= to; ++i) res.push(i);
    return res;
}

The tricky solution would be like this:

function range(from, to) { 
    return [...Array(to - from + 1).keys()].map(function(x){return x + from});
}

EDIT: If you are really determined, you can make everything an expression:

(function(a, b){return [...Array(b-a+1).keys()].map(function(x){return x+a;})})(2000, new Date().getFullYear())

:)

Radek
  • 846
  • 4
  • 17
  • I thought ES2015+ has more straightforward way, but apparently it does not.. Thank you anyway. – yskkin Aug 13 '18 at 22:20