'Efficient way to create and fill an array with consecutive numbers in range
for the moment i use this JavaScript to create an array with n numbers from 0 to n
// javascript populate array
var n=1000;
var arr=[n];
for (i=n;i>=0;i--) {
arr[i]=i;
console.log(arr[i]);
}
is it the fast/right way to do the task?
Solution 1:[1]
An ES6 way of doing it using Array.keys():
let n = 10;
let arr = Array.from(Array(n).keys());
console.log(arr);
Made a quick JSPerf with answer so far:
Solution 2:[2]
You can use the function map skipping the first param of the predicate and getting the index i.
let arr = Array(10).fill().map((_, i) => i);
console.log(arr);
Solution 3:[3]
If by efficient you mean ‘least number of characters’, I think this is shorter than any of the answers posted:
[...Array(10).keys()]
Things like this come in handy when testing stuff using the browser console. Be warned though that it's more than twice as slow as the currently accepted answer of:
Array.from({length:10},(e,i)=>i)
Although I haven't professionally tested the performance, I tried creating an array with 1e8 elements using both methods and it took about five seconds using the first method and just two using the second method (with considerable variability for both methods) on my little laptop whereas an array with 1e9 elements caused it to run out of memory.
But for people who need to enter stuff like this into the browser console regularly, that might not matter as much as ease of remembrance and entry. Note however that if you're going to feed the result immediately into a .map() the first method is only one character shorter and the performance will be even worse in comparison, particularly because the second method doesn't need a separate .map() call. So, only for debugging or trying stuff out, but still useful in my opinion.
Solution 4:[4]
The shortest way (I think) [...Array(10)].map((a,b)=>b)
console.log(
[...Array(10)].map((a,b)=>b)
)
Solution 5:[5]
Array.from(Array(1000).keys());
Is the fasted so far in v8 engine.
Dont listent other.
https://jsbench.me/jdjxrdszul/2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ele |
| Solution 3 | Anonymous |
| Solution 4 | Luis felipe De jesus Munoz |
| Solution 5 | jon |
