How to use the drop method in Lodash
Overview
The drop method can get the slice of the array by dropping the provided n elements from the beginning.
Syntax
_.drop(array, [n=1])
Parameters
This method takes the following two arguments:
-
array: The array from which elements to be taken. -
n: Number of elements to be dropped from the beginning. It is an optional argument. The default value is1(It returns a new array without the first element).
Return value
This method drops the provided n elements and returns the remaining part as a new array.
Note: The source array remains unaffected.
Example
The code below demonstrates how to use the drop method in Lodash:
Explanation
-
Line 6: We load the
lodashlibrary file from the server link. -
Line 8: We create an array
arrwith[1,2,3,4,5]as elements. -
Line 12: We call the
dropmethod with the variablearrand2as arguments. Thedropmethod will drop the first two elements of the array, create a new array with the remaining elements, and return it. The result is[3,4,5]. -
Line 15: We call the
dropmethod with the variablearrand4as arguments. Thedropmethod will drop the first four elements of the array and return[5]as a result.