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:

  1. array: The array from which elements to be taken.

  2. n: Number of elements to be dropped from the beginning. It is an optional argument. The default value is 1 (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:

Console
Using the drop method

Explanation

  • Line 6: We load the lodash library file from the server link.

  • Line 8: We create an array arr with [1,2,3,4,5] as elements.

  • Line 12: We call the drop method with the variable arr and 2 as arguments. The drop method 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 drop method with the variable arr and 4 as arguments. The drop method will drop the first four elements of the array and return [5] as a result.

Free Resources