Have you ever needed to create an array that has some unknown number of members and each member has a unique value? I recently did and stumbled across several Stack Overflow answers that put together an elegant solution:
const quantity = 20;
const myArray = [...Array(quantity).keys()];
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
That's all she wrote folks!
Array(quantity)
uses the Array object to create an array of a given size.
The rest of it simply using ES6 array destructuring to spread the keys of the array (the array is of size X and there is a key for each member) into a new array.
* Most of this was taken from https://stackoverflow.com/questions/4852017/how-to-initialize-an-arrays-length-in-javascript. I can't remember where I got the .keys
part of it.
Alternative Solutions
Here are some other ways to create arrays of dynamic sizes. Unfortunately, none of them generate unique members.
const quantity = 20;
const myArray = Array(20);
// Just creates an array of empty elements
// [empty × 20]
const quantity = 20;
const myArray = Array(quantity).fill(0)
// Creates an array with 20 members whose values are all 0
// [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
Of course, you could use some loops or maps to fill the array with unique values, but the first solution seems to be the most elegant while also being easy to read.