Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Array.map with new Array constructor

I was trying to use new Array() constructor with map in order to create a one-line code that creates a list of elements. Something like this :

let arr = new Array(12).map( (el, i) => {
  console.log('This is never called');
  return i + 1;
});

Reading docs, the behaviour makes sense.

Basically docs say that callback of map will be executed even for declared undefined values in array, but not for example when creating empty Arrays like the code before.

So this should work :

var arr = new Array(12);

for(let i = 0; i < arr.length ; i++){
  arr[i] = undefined;
}

let list = arr.map( (e, i) => {
  console.log(i + 1);
  return i + 1;
});

So, We also can do something like this :

let newArray = (length) => {
  let myArray = new Array(length);
  for(let i = 0; i < length; i++) myArray[i] = undefined;
  return myArray;
};

console.log( newArray(12).map( (el, i) => i + 1 ) );

So my question. Is there a better/pretty way to do it with map function ?

Thanks in advance!

like image 495
Jose Hermosilla Rodrigo Avatar asked May 27 '16 15:05

Jose Hermosilla Rodrigo


Video Answer


2 Answers

You can use Array#from to create an array having passed length.

Array.from({length: 12}, (e, i) => i + 1);
like image 168
Tushar Avatar answered Oct 20 '22 06:10

Tushar


If I am not mistaken, you explicitly said that you wanted an answer with new Array constructor.

Here is how to do it. One line, beautiful ES6:

let me = [...new Array(5)].map((x,i)=>i)
// [0,1,2,3,4]

Explanation:

  1. new Array(5) generates this: [ , , , , ]​​​​​
  2. [...new Array(5)] is a shorthand for Array.from(new Array(5)), and generates this: ​​​​​[ undefined, undefined, undefined, undefined, undefined ]​​​​​, that is an array of undefined objects. Yes, undefined is a value (a primitive one :) ).
  3. Now we can iterate over the values of our brand new array :D

PS: you can even skip the new keyword and do:

[...Array(5)].map((x,i)=>i)
like image 44
Soldeplata Saketos Avatar answered Oct 20 '22 07:10

Soldeplata Saketos