rob.m
rob.m

Reputation: 10571

How could I create an array on the fly?

I have the following:

    $("#years").ionRangeSlider({
      type: "double",
      grid: true,
      min: 0,
      from: 10,
      to: 11,
      max: 2018,
      prettify_enabled:false,
      values: [
          "1910", "1920", "1930",
          "1940", "1950", "1960",
          "1970", "1980", "1990",
          "2000", "2010", "2018"
      ]
    });

I need to be able to generate from 0 to 2018 on this part

      values: [
          "1910", "1920", "1930",
          "1940", "1950", "1960",
          "1970", "1980", "1990",
          "2000", "2010", "2018"
      ]

But I can't go manually as they're 2 thousands values. So I thought of using a loop, something like

for(var i = 0; i < 2018; i++;) {

} 

However, I am not sure how would I generate the object

      [
          "0", .... , "2018"
      ]

Upvotes: 1

Views: 799

Answers (4)

rottitime
rottitime

Reputation: 2461

An even shorter code:

[...Array(20).keys()]

document.write([...Array(20).keys()]);

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

You can use Array#from()

Array.from({length: currentYear + 1}, (_,i) => i)

Upvotes: 2

msanford
msanford

Reputation: 12227

To adapt Li357's (or any) answer so you don't have to change this code every new year's:

Array((new Date()).getFullYear() + 1).fill().map((_, i) => i)

And in this case, probably also set your ionRangeSlider's max: value to this as well.

So set a variable somewhere and use it, because creating new Date() can be a bit heavy.

Upvotes: 2

Andrew Li
Andrew Li

Reputation: 57944

You can create an array with 2019 slots (for 0 to 2018 inclusive) and fill then map to its index:

Array(2019).fill().map((_, i) => i)

And if you want a string you can coerce via concatenation or interpolation:

Array(2019).fill().map((_, i) => `${i}`)

Upvotes: 9

Related Questions