22

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, .......];

3 Answers 3

36

That should do the tricks:

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

eg:

_.times(5, _.constant(null));
[null, null, null, null, null]
Sign up to request clarification or add additional context in comments.

1 Comment

what about if i want to fill existent array ?
22
_.fill(Array(arrayLength), null)

// exemple:
_.fill(Array(5), null); // [ null, null, null, null, null ]

EDIT:

I made some performance tests: https://jsperf.com/lodash-initialize-array-fill-vs-times

  • _.fill is faster than _.times
  • null is faster than _constant(null)

1 Comment

It’s this faster than make a for loop and push x times null to my array???
4

I'd suggest using _.fill

_.fill(Array(myArrayLength), null);`

It seems to be faster than _.times, at least it is on Chrome.

See perf comparison here: https://jsperf.com/fill-vs-times/1

2 Comments

Duplicate answer.
It’s this faster than write a loop and make array.push. Just curious

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.