Search code examples
javascriptarraysmap-function

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!


Solution

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

    Array.from({length: 12}, (e, i) => i + 1);