javascript

Replace array values with another value Lodash

If you want to replace array items value with another value and you are using lodash in your project. Then you can use the .fill() method of lodash to replace them.

//REPLACE BY PASSING NEW VALUE ONLY
var arr = [1, 2, 3, 4, 5, 6];

_.fill(arr, '*');
console.log(arr);
// => ["*","*","*","*","*","*"]

_.fill(arr, 2);
console.log(arr);
// => [20,"#","#",70,80,90]

//REPLACE BY PASING - Value, start, end
const arr2 = [20, 50, 60, 70, 80, 90];
const start = 1;
const end = 3;
_.fill(arr2, '#', 1, 3);
console.log(arr2);
// => [20,"#","#",70,80,90]

_.fill Lodash

You can fill your array with some value using this lodash function. The basic syntax of the method is as below.

_.fill(Array, Value, Start=0, End=Array.length);

The fill method takes 4 parameters in which the first two parameters are required and the last two parameters are optional. 

 Array: This is a required parameter and it contains the values that need to be replaced.

Value: This is also a required parameter and this is the value that needs to be replaced with array values.

Start: This is an optional parameter and it is the index from where you want to replace the value in the array. The default value for this parameter is 0 means if you do not pass anything to it, it will start from index 0.

End: This is an optional parameter and you can pass the index value to which position you want to fill the value. The default value of this parameter is Array.length.

Example Demo

Was this helpful?