-1

I am trying to refactor years so it is more dynamic and can be created using the start of the year (2010) and the end of the year (2018).

Initially, I used a for loop to solve it but I was wondering if there was a better way to refactor years.

Current setup:

const years = [
  {
    value: 2010,
    label: '2010',
  },
  {
    value: 2011,
    label: '2011',
  },
  {
    value: 2012,
    label: '2012',
  },
  {
    value: 2013,
    label: '2013',
  },
  {
    value: 2014,
    label: '2014',
  },
  {
    value: 2015,
    label: '2015',
  },
  {
    value: 2016,
    label: '2016',
  },
  {
    value: 2017,
    label: '2017',
  },
  {
    value: 2018,
    label: '2018',
  },
]

What I have tried:

const startYear = 2010;
const endYear = 2019;
const yearsArray = new Array();
for (let i = startYear; i < endYear; i += 1 ){
  yearsArray.push({value: i, label: JSON.stringify(i)})
}
Maggie
  • 3
  • 2
  • 1
    please add what you like to get and what you have tried. – Nina Scholz Aug 25 '21 at 08:12
  • If you are looking for a range function, that generates the above, then see here: https://stackoverflow.com/q/3895478/1220550 - Note that you'll need to extend whichever you choose to create the `value` and `label` properties instead of just numbers. – Peter B Aug 25 '21 at 08:27
  • @PeterB Range-generating functions like that are generally horribly inefficient compared to a plain ol' regular for loop. – AKX Aug 25 '21 at 08:29

1 Answers1

0

A for loop is just the ticket here.

const years = [];
for (let year = 2010; year <= 2018; year++) {
  years.push({value: year, label: `${year}`});
}

is perfectly fine to generate the same list of objects.

AKX
  • 152,115
  • 15
  • 115
  • 172