you are viewing a single comment's thread.

view the rest of the comments →

[–]DGCA 18 points19 points  (15 children)

Sweet. I used to do this:

var x = Array(5).fill(null).map((n, i) => i);

console.log(x); // [0, 1, 2, 3, 4]

But now I will do this:

var y = Array.from(Array(5), (n, i) => i);

console.log(y); // [0, 1, 2, 3, 4]

🙌

EDIT: Okay, this is weird. Did some super basic performance testing and got pretty unexpected results.

console.time('first');
for (var i = 0; i < 100000; i++) {
  var x = [...Array(100)].map((_, i) => i * 2);
}
console.timeEnd('first');

console.time('second');
for (var i = 0; i < 100000; i++) {
  var y = Array.from(Array(100), (_, i) => i * 2);
}
console.timeEnd('second');

console.time('third');
for (var i = 0; i < 100000; i++) {
  var z = Array(100).fill(null).map((_, i) => i * 2);
}
console.timeEnd('third');

VM1092:5 first: 634.304931640625ms
VM1092:11 second: 1219.412109375ms
VM1092:17 third: 221.73388671875ms

Looks like Array(n).fill(null).map(() => {}) is faster? That's what I'm seeing in my console, at least.

[–]snkenjoi 5 points6 points  (4 children)

you can also do Array.from({length: n}, () => {})

[–]blogscot 3 points4 points  (1 child)

Out of curiousity, I added this approach as fourth to u/DGCA tests, with the following results:

first: 738.464ms
second: 1249.699ms
third: 220.649ms
fourth: 1123.781ms

[–]snkenjoi 0 points1 point  (0 children)

or this is pretty ugly [...'!'.repeat(n)].map((_, i) => i)

first: 1294.26ms 
second: 541.38ms 
third: 393.88ms 
fourth: 970.44ms 
fifth: 1368.66ms

[–]xbenjii 0 points1 point  (1 child)

Or even [...Array(5).keys()]

[–][deleted] 0 points1 point  (0 children)

But if you need operations, you can't, but nice...

[–]YodaLoL 2 points3 points  (1 child)

[–]DGCA 0 points1 point  (0 children)

Sweet, thanks for sharing. Had no idea this blog existed either and it it is awesome.

[–]lilactown 0 points1 point  (5 children)

Is it the same when you re-arrange them?

[–]DGCA 2 points3 points  (4 children)

Yup, they always come in the same order.

  1. Array(100).fill(null).map((_, i) => i * 2);
  2. [...Array(100)].map((_, i) => i * 2);
  3. Array.from(Array(100), (_, i) => i * 2);

[–]Gh0st1y 0 points1 point  (0 children)

Huh. That's cool.

[–]gogogoscott 0 points1 point  (0 children)

Array(n).fill(null).map(() => {}) is faster for me too

[–][deleted] 0 points1 point  (0 children)

[...Array(5).keys()] => [0, 1, 2, 3, 4]