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

Hello,

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.

image

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

Thanks!

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

var year = [];
for(i=0;i<=62;i++){
  year.push(moment().subtract(i,'year').format("YYYY"));
  
}
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:

3 Likes

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.

[...new Array(moment().year()-1960+1)].map((_,i) => i+1960).sort((a,b) => b-a)
// OR even shorter
[...new 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 [...new Array(moment().year()-{{stateMinYear.value}}+1)]
    .map((_,i) => i+{{stateMinYear.value}})
    .sort((a,b) => b-a)
2 Likes

this is great, thanks @rferland