A good[ish] website
Web development blog, loads of UI and JavaScript topics
Fill long arrays with content. There are times when you need arrays filled with nothing particular.
Maybe the most obvious way is to fill the array with a while
loop (or for
loop would do just as well):
let count = 0
const arr = []
while (count < 1000) {
arr.push(count)
count++
}
console.log(arr)
If you call the array constructor function with an integer as a param, it will give you an empty array of n length:
const emptyArray = new Array(100)
console.log(emptyArray)
If you loop the empty array, the values will be undefined
:
for (const arrayItem of emptyArray) {
console.log(arrayItem) // undefined
}
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)
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]
Below are few nifty examples that might come handy.
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.
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()
You can then render the emoji with React for example using String.fromCodePoint()
:
<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):
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.