Thursday, December 26, 2024
Google search engine
HomeLanguagesJavascriptLodash _.fill() Method

Lodash _.fill() Method

Lodash is a library that works on the top of underscore.js. It proves to be very handy when it is used with objects, arrays, dictionaries and strings. The lodash.fill() method is used to fill a set of values into the array in a given range.

Syntax:

lodash.fill(array, value, startIndex, endIndex)

Parameters:

  • Array: It is the original array that is to be filled with certain values.
  • Value: Value to be filled in the array.
  • startIndex: It is the index from where value is to be filled.
  • endIndex: It is the index to which values are to be filled in the array.

Note:

  • All index less then endIndex are included except endIndex.
  • Changes are done in the original array.

Return Value: It return the array.

Example 1:

Javascript




// Requiring the lodash library
let lodash = require("lodash");
 
// Original array
let array = [2, 2, 3, 4, 5, 6]
 
// Printing original array
console.log("Before : ", array)
 
// Using fill() method to replace
// values in range (0, 4]
lodash.fill(array, 10, 0, 4)
 
// Printing original array again
console.log("After : ", array)


Output:

Example 2: When empty array is given. 

Javascript




undefined


// Requiring the lodash library
let lodash = require(“lodash”);

// Original array
let array = Array(10)

// Printing original array
console.log(“Before : “, array)

// Using fill() method to add
// values in range (0, 4]
lodash.fill(array, 10, 0, 4)

// Printing original array again
console.log(“After : “, array)

Output:

Example 3: when endIndex is greater than the size of array.

Javascript




// Requiring the lodash library
let lodash = require("lodash");
 
// Original array
let array = [{ "aa": 1 },
        { "bb": 1 }, "a", "b"]
 
// Printing original array
console.log("Before : ", array)
 
// Using fill() method to replace
// values in range (0, 10] greater
// then size of array
lodash.fill(array, 10, 0, 10)
 
// Printing original array again
console.log("After : ", array)


Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments