Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, .......];
like image 650
Rk R Bairi Avatar asked Mar 03 '16 16:03

Rk R Bairi


People also ask

How do you create a zero filled array of a desired length?

Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.

How do you set the length of an array?

If you want to change the size, you need to create a new array of the desired size, and then copy elements from the old array to the new array, and use the new array. In our example, arr can only hold int values. Arrays can hold primitive values, unlike ArrayList, which can only hold object values.

How do you remove undefined and null values from an object using Lodash?

To remove a null from an object with lodash, you can use the omitBy() function. If you want to remove both null and undefined , you can use . isNil or non-strict equality.

Is null or undefined Lodash?

Lodash helps in working with arrays, strings, objects, numbers, etc. The _. isNil() method is used to check if the value is null or undefined. If the value is nullish then returns true otherwise it returns false.


2 Answers

That should do the tricks:

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

eg:

_.times(5, _.constant(null));
[null, null, null, null, null]
like image 132
Julien Leray Avatar answered Sep 20 '22 16:09

Julien Leray


_.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)
like image 30
Boris Avatar answered Sep 21 '22 16:09

Boris