clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

JavaScript: make arrays of size | how to create filler arrays of varying length

Filed under: JavaScript— Tagged with: Iteration

Stuff arbitrarily sized arrays with content. There are times when you need long winding arrays filled with monotonic content.

Push into the array

The most obvious way is to fill the array with a while loop (or for loop would just as well):

let count = 0
const arr = []

while (count < 1000) {
  arr.push(count)
  count++
}

console.log(arr)

Fill arrays with the array constructor

If you call the array constructor function with a int as a param, it will give you an empty array of n length:

const emptyArray = new Array(100)
console.log(emptyArray)
Empty array with a length of 100
[empty x 100] array

If you loop the empty array, the values will be undefined:

for (const arrayItem of emptyArray) {
  console.log(arrayItem) // undefined
}

Filling arrays with fill()

After you’ve created your empty array, it can be filled with values using the fill method, in this case just with zeros:

const filledArray = new Array(100).fill(0)

Packing arrays with Array.from()

With Array.from() you can make an array from anything that is iterable, a string for example:

Array.from('foo') // [f, o, o]

Or you can configure its length:

Array.from({ length: 4 }) // [undefined, undefined, undefined, undefined]

The Array.from() method can take a second parameter: a function, with which you can map values into to the empty array:

Array.from({ length: 5 }, (x, i) => i) // [1, 2, 3, 4, 5]

It can also take an array as its first argument, and then further map values into that array:

const existingArray = [100, 200, 300, 400, 500]
Array.from(existingArray, (x, i) => x + i) // [100, 201, 302, 403, 504]

Few examples

Below are few nifty examples that might come handy.

Fill array with random numbers

The content can be anything, random numbers for example:

const getRandomInt = max => Math.floor(Math.random() * max)
const randomNumbers = Array.from({ length: 1000 }, () => getRandomInt(100))

That would be a list of 1000 random integers, with a max size of 100.

Fill array with ranges, like the emoji unicode ranges

The Array.from() method is pretty cool, for example you can define a 2D array of emoji ranges, then map that outer dimension and process the innards with Array.from(), then flat it, and you’ve got a nice array of emoji, only with few lines of code:

const emojiRange = [
  [128513, 128591],
  [128640, 128704],
  [9986, 10160]
]

const emojis = emojiRange
  .map(([start, end]) =>
    Array.from({ length: end - start }, (x, i) => i + start)
  )
  .flat()

In React you can render the emojis like so:

<div>
  {emojis.map(emoji => (
    <span title={`&#${emoji};`}>{String.fromCodePoint(emoji)}</span>
  ))}
</div>

It produces all the emoji and dingbats:

😁😂😃😄😅😆😇😈😉😊😋😌😍😎😏😐😑😒😓😔😕😖😗😘😙😚😛😜😝😞😟😠😡😢😣😤😥😦😧😨😩😪😫😬😭😮😯😰😱😲😳😴😵😶😷😸😹😺😻😼😽😾😿🙀🙁🙂🙃🙄🙅🙆🙇🙈🙉🙊🙋🙌🙍🙎🚀🚁🚂🚃🚄🚅🚆🚇🚈🚉🚊🚋🚌🚍🚎🚏🚐🚑🚒🚓🚔🚕🚖🚗🚘🚙🚚🚛🚜🚝🚞🚟🚠🚡🚢🚣🚤🚥🚦🚧🚨🚩🚪🚫🚬🚭🚮🚯🚰🚱🚲🚳🚴🚵🚶🚷🚸🚹🚺🚻🚼🚽🚾🚿

Here’s a CodeSandbox of a vanilla JS example (it’s almost the same, tho):

Edit fill-arrays-with-emoji

Conclusions

2ality in his article goes deeper into the nitty-gritty of array creation, if you’re interested in the underlying V8 parser engine behavior etc.

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.

  • © 2021 Antti Hiljá
  • About
  • Follow me in Twatter → @hiljaa
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • console.log('Smash the patriarchy!')
  • I love u!