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, .......];
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.
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.
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.
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.
That should do the tricks:
_.times(arrayLength, _.constant(null));
eg:
_.times(5, _.constant(null));
[null, null, null, null, null]
_.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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With