What\'s the most efficient way to create this simple array dynamically.
var arr = [ \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\"];
<
var arr = [];
while(mynumber--) {
arr[mynumber] = String(mynumber+1);
}
The same way you would for all arrays you want to fill dynamically. A for loop. Suedo code is
arr =array()
for(i; i<max; i++){
arr[]=i
}
that should help you on the way
Some of us are referring to use from which is not good at the performance:
function getArrayViaFrom(input) {
console.time('Execution Time');
let output = Array.from(Array(input), (value, i) => (i + 1).toString())
console.timeEnd('Execution Time');
return output;
}
function getArrayViaFor(input) {
console.time('Execution Time 1');
var output = [];
for (var i = 1; i <= input; i++) {
output.push(i.toString());
}
console.timeEnd('Execution Time 1');
return output;
}
console.log(getArrayViaFrom(10)) // Takes 10x more than for that is 0.220ms
console.log(getArrayViaFor(10)) // Takes 10x less than From that is 0.020ms
var arr = [];
for(var i=1; i<=mynumber; i++) {
arr.push(i.toString());
}
This answer is about "how to dynamically create an array without loop".
Literal operator []
doesn't allow us to create dynamically, so let's look into Array
, it's constructor and it's methods.
In ES2015 Array has method .from()
, which easily allows us to create dynamic Array:
Array.from({length: 10}) // -> [undefined, undefined, undefined, ... ]
When Array's constructor receives number as first parameter, it creates an Array with size of that number, but it is not iterable, so we cannot use .map()
, .filter()
etc. :
new Array(10) // -> [empty × 10]
But if we'll pass more than one parameter we will receive array from all parameters:
new Array(1,2,3) // -> [1,2,3]
If we would use ES2015 we can use spread operator which will spread empty Array inside another Array, so we will get iterable Array :
[...new Array(10)] // -> [undefined, undefined, undefined, ...]
But if we don't use ES2015 and don't have polyfills, there is also a way to create dynamic Array without loop in ES5. If we'll think about .apply()
method: it spreads second argument array to params. So calling apply on Array's constructor will do the thing:
Array.apply(null, new Array(10)) // -> [undefined, undefined, undefined, ...]
After we have dynamic iterable Array, we can use map to assign dynamic values:
Array.apply(null, new Array(10)).map(function(el, i) {return ++i + ""})
// ["1","2","3", ...]
I would do as follows;
var num = 10,
dynar = [...Array(num)].map((_,i) => ++i+"");
console.log(dynar);