Create array of years in JS for use in in dropdown input


I'm trying to create an array of years, in descending order, as the options for a select input.

I've been trying but failing to do this with javascript but can't figure it out.

The end result should look like this, except I'd like the years to go back to 1960.


Is anyone able to help me with the correct js to use as the data source?


You can use moment.js
If you only want to go back to 1960 from today you can iterate like so

var year = [];
return year;

Though the number 62 is relative as that could change this coming January so you may want to consider using a variable there (count the number of years back to 1960. But this is the quick and dirty way :slight_smile:


thanks a lot @ScottR ! I didn't know moment was built into retool, really useful.

Same in one-liner format using 1960 as reference instead of X years.

[ Array(moment().year()-1960+1)].map((_,i) => i+1960).sort((a,b) => b-a)
// OR even shorter
[ Array(moment().year()-1960+1)].map((_,i) => i+1960).reverse()

You could then define 1960 in a state variable and the script in a transformer for maintainability

return [ Array(moment().year()-{{stateMinYear.value}}+1)]
    .map((_,i) => i+{{stateMinYear.value}})
    .sort((a,b) => b-a)

this is great, thanks @rferland