Search code examples
javascripthtmlarraystypescriptlit

Can modern javascript create an array of X number of things? (like `map` but on a number rather than an array)


Given a number x , What's the nicest way of saying give me x number of a given string, object, whatever, and put them all in an array.

Ideally they'd have access to their index and that's about it.

I know I can create an array and push to that in a for loop (with i < x;) but I'd like it cleaner, and native, please.

This kind of syntax:

const arrayOfDivs = numberOfDivs.repeat(idx => html`<div id=${idx}></div>`;

// numberOfDivs == 3
arrayOfDivs == [
  '<div id=${0}></div>' , 
  '<div id=${1}></div>' ,
  '<div id=${2}></div>'   
]

And if there's no way like this, what do other people use, and can someone ask javascript to invent it?

I do a for loop and push to an array usually, but I remember creating a [0,1,2,3,4] array from the number before and .maping from that, bad times!

Thanks


Solution

  • like map

    Array.from has a very similar API to map. You could supply it with a number that goes to .length property of the first argument:

    function createSeveral<Item>(count: number, itemFactory: () => Item): Item[] {
      return Array.from({ length: count }, itemFactory) as Item[];
    }
    

    So, for your case, you could use it like this:

    Array.from({ length: numberOfDivs }, (_, i) => html`<div id=${i}></div>`)