Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The Lodash.initial() function is used to get the all elements of the array in range 0 to n-2. Thereby getting all elements except the (n-1)th element.
Syntax:
Lodash.initial( arrayObject )
Parameters:
- arrayObject: There is only one parameter of type array.
Return Value: It returns an array object.
Note: Install lodash module by npm install lodash
before using the below-given code.
Example 1: When an array of objects is given.
// Requiring the lodash library const _ = require( "lodash" ); // Original array let array1 = [ { "a" : 1, "b" : 2 }, { "a" : 1 }, { "b" : 1 } ] // Using _.initial() function to get // all elements of the array in // range (0,n-2]) let initialArray = lodash.initial(array1); // Original Array console.log( "original Array: " , array1) // Printing the initialArray console.log( "initial Array: " , initialArray) |
Output:
Example 2:
// Requiring the lodash library const _ = require( "lodash" ); // Original array let array1 = [1, 2, 3, 4] // Using _.initial() function to // get all elements of the array // in range (0,n-2]) let initialArray = lodash.initial(array1); // Original Array console.log( "original Array: " , array1) // Printing the initialArray console.log( "initial Array: " , initialArray) |
Output:
Example 3: When an array of size one is given it returns the empty array.
// Requiring the lodash library const _ = require( "lodash" ); // Original array let array1 = [1] // Using _.initial() function to // get all elements of the array // in range (0,n-2]) let initialArray = lodash.initial(array1); // Original Array console.log( "original Array: " , array1) // Printing the initialArray console.log( "initial Array: " , initialArray) |
Output: