Syntax, Parameter, and Return Value
Syntax:
_.drop(array, [n=1])
Parameters:
-
array (Array): The array to query.
- n (number): The number of elements to drop from the beginning of the array. Defaults to 1 if not specified.
Return Value:
Returns the slice of array.
Examples with Proper Codes
Example 1: Basic Usage
JavaScript
const _ = require('lodash');
const array = [1, 2, 3, 4, 5];
const result = _.drop(array, 2);
console.log(result);
You can also try this code with Online Javascript Compiler
Run Code
Output:
[3, 4, 5]
Dropping the first two elements of the array.
Example 2: Default Behavior
JavaScript
const array = ['a', 'b', 'c'];
const result = _.drop(array);
console.log(result);
You can also try this code with Online Javascript Compiler
Run Code
Output:
['b', 'c']
When no number is specified, _.drop() defaults to dropping the first element.
Example 3: Dropping No Elements
JavaScript
const array = [1, 2, 3];
const result = _.drop(array, 0);
console.log(result);
You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, 3]
Specifying 0 will not drop any elements.
Example 4: Non-Integer Values
JavaScript
const array = ['apple', 'banana', 'cherry'];
const result = _.drop(array, 1.5);
console.log(result);
You can also try this code with Online Javascript Compiler
Run Code
Output:
['banana', 'cherry']
Non-integer values are floored, resulting in the dropping of one element in this case.
Frequently Asked Questions
What happens if n is larger than the array's length in _.drop()?
If n exceeds the array's length, _.drop() returns an empty array, as all elements are dropped.
Can _.drop() modify the original array?
No, it returns a new array, leaving the original array unmodified.
Is there a method to drop elements from the end of the array?
Yes, Lodash provides _.dropRight() which works similarly but drops elements from the end of the array.
Conclusion
The _.drop() method in Lodash is a simple yet powerful tool for array manipulation, providing an easy way to remove elements from the beginning of an array. Its straightforward syntax and efficient operation make it an essential function in many JavaScript data manipulation scenarios. Whether dealing with large datasets or needing quick array modifications, _.drop() proves to be an invaluable asset in a developer's toolkit.
You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.