Search code examples
javascriptarraysunderscore.jslodash

Lodash/underscore function to Initialize an array with default null values of a given length


Is there a function in lodash to initialize an array with default null values for a given length?

Array method currently using :

     var myArray = Array.apply(null, Array(myArrayLength)).map(function() { return null });

Lodash Function trying to use :

     var myArray = _.times(myArrayLength, null);

Required array :

  var myArray = [null, null, .......];

Solution

  • That should do the tricks:

    _.times(arrayLength, _.constant(null));
    

    eg:

    _.times(5, _.constant(null));
    [null, null, null, null, null]