What's the most efficient way to create this simple array dynamically.
var arr = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
Let's say we can get the number 10 from a variable
var mynumber = 10;
This question is related to
javascript
var arr = [];
while(mynumber--) {
arr[mynumber] = String(mynumber+1);
}
Some of us are referring to use from which is not good at the performance:
function getArrayViaFrom(input) {_x000D_
console.time('Execution Time');_x000D_
let output = Array.from(Array(input), (value, i) => (i + 1).toString())_x000D_
console.timeEnd('Execution Time');_x000D_
_x000D_
return output;_x000D_
}_x000D_
_x000D_
function getArrayViaFor(input) {_x000D_
console.time('Execution Time 1');_x000D_
var output = [];_x000D_
for (var i = 1; i <= input; i++) {_x000D_
output.push(i.toString());_x000D_
}_x000D_
console.timeEnd('Execution Time 1');_x000D_
_x000D_
return output;_x000D_
}_x000D_
_x000D_
console.log(getArrayViaFrom(10)) // Takes 10x more than for that is 0.220ms_x000D_
console.log(getArrayViaFor(10)) // Takes 10x less than From that is 0.020ms
_x000D_
A little late to this game, but there is REALLY cool stuff you can do with ES6 these days.
You can now fill an array of dynamic length with random numbers in one line of code!
[...Array(10).keys()].map(() => Math.floor(Math.random() * 100))
var arr = [];
for(var i=1; i<=mynumber; i++) {
arr.push("" + i);
}
This seems to be faster in Chrome, according to JSPerf, but please note that it is all very browser dependant.
There's 4 things you can change about this snippet:
for
or while
.push
or direct access by index.toString
.In each and every browser total speed would be combination of how much better each option for each item in this list performs in that particular browser.
TL;DR: it is probably not good idea to try to micro-optimize this particular piece.
I hope you have to get last element from array variable so my solution
var arr = [ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];
var mynumber = arr [arr .length - 1];
//var mynumber = 10;
If you are asking whether there is a built in Pythonic range
-like function, there isn't. You have to do it the brute force way. Maybe rangy would be of interest to you.
Sounds like you just want to construct an array that contains the string versions of the integer values. A simple approach:
var arr = [];
for (var i = 1; i <= mynumber; i++) arr.push(""+i);
For a more interesting version you could do a generator...
function tail(i, maxval) {
return [i].concat(i < maxval ? tail(i+1, maxval) : []);
}
var arr = tail(1, mynumber);
misread the question, corrected. Try:
var myNumber = 100,
myarr = (function arr(i){return i ? arr(i-1).concat(i) : [i]}(myNumber));
Just for fun, if you extend Array
like this:
Array.prototype.mapx = function(callback){
return String(this).split(',').map(callback);
}
You could use:
var myNum = 100,
myarr = new Array(myNum).mapx(function(el,i){return i+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
Update: micro-optimizations like this one are just not worth it, engines are so smart these days that I would advice in the 2020 to simply just go with
var arr = [];
.
Here is how I would do it:
var mynumber = 10;
var arr = new Array(mynumber);
for (var i = 0; i < mynumber; i++) {
arr[i] = (i + 1).toString();
}
My answer is pretty much the same of everyone, but note that I did something different:
So I created the array with new Array(mynumber);
I would do as follows;
var num = 10,_x000D_
dynar = [...Array(num)].map((_,i) => ++i+"");_x000D_
console.log(dynar);
_x000D_
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 had a similar problem and a solution I found (forgot where I found it) is this:
Array.from(Array(mynumber), (val, index) => index + 1)
for (var j = 0; j <= data.legth -1; j++) {
lang += data.lang +", " ;
}
var langs = lang.split(',')
console.log("Languages =>", lang, typeof(lang), typeof(langs), langs)
console.log(lang[0]) // here access arrary by index value
you can see the type of string and object
With ES2015, this can be achieved concisely in a single expression using the Array.from
method like so:
Array.from({ length: 10 }, (_, idx) => `${++idx}`)
The first argument to from
is an array like object that provides a length property. The second argument is a map function that allows us to replace the default undefined
values with their adjusted index values as you requested. Checkout the specification here
Source: Stackoverflow.com