0

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

  • `const arr = new Array(x).fill(0).map((_, idx) => html\`
    \`)`
    –  Oct 07 '21 at 13:02
  • Does this answer your question? [Repeat String - Javascript](https://stackoverflow.com/questions/202605/repeat-string-javascript) – ziishaned Oct 07 '21 at 13:02
  • [`Array.from`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) allows as second argument a mapper function ... ``Array.from({ length: 3 }, (_, idx) => html`
    `)``
    – Peter Seliger Oct 07 '21 at 14:11

2 Answers2

4

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>`)
Parzh from Ukraine
  • 7,999
  • 3
  • 34
  • 65
  • By the way, some time in the past I've published (as a joke) an npm package called `iterable-numbers` (https://www.npmjs.com/package/iterable-numbers), which allows doing `Array.from(5)`. This might be useful in your case (although, mutating prototypes of builtin objets is a bad idea). – Parzh from Ukraine Oct 07 '21 at 13:22
  • Yeah i like this thanks. It could do with being _ever so slightly_ simpler but this is the best i've seen – StrangerStrings Oct 07 '21 at 13:23
  • I like your npm lol, obviously thinking on the same tracks, i don't like using things like that though that change core behavior – StrangerStrings Oct 07 '21 at 14:17
1

In ES6, you can create an array containing elements 1 to n using the spread syntax and Array.prototype.keys() (which you could then .map as you mentioned):

const arr = [...Array(10).keys()];
// arr => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If you want the same object repeated n times, you can use Array.prototype.fill():

const arr = Array(5).fill('x');
// arr => ['x', 'x', 'x', 'x', 'x']
Luke Carr
  • 553
  • 5
  • 18