Syntax, Parameter, and Return Value
Syntax:
_.dropRight(array, [n=1])
Parameters:
-
array (Array): The array to process.
- n (number): The number of elements to drop from the end. 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 = _.dropRight(array, 2);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
[1, 2, 3]
Dropping the last two elements of the array.
Example 2: Default Behavior
JavaScript
const array = ['a', 'b', 'c'];
const result = _.dropRight(array);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
['a', 'b']
When no number is specified, _.dropRight() defaults to dropping the last element.
Example 3: Dropping No Elements
JavaScript
const array = [1, 2, 3];
const result = _.dropRight(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 from the end.
Example 4: Non-Integer Values
JavaScript
const array = ['apple', 'banana', 'cherry'];
const result = _.dropRight(array, 1.5);
console.log(result);

You can also try this code with Online Javascript Compiler
Run Code
Output:
['apple', 'banana']
Non-integer values are floored, resulting in the dropping of the last element in this case.
Frequently Asked Questions
What if n exceeds the array's length in _.dropRight()?
If n is greater than the array's length, the function returns an empty array, as all elements are dropped from the end.
Does _.dropRight() affect the original array?
No, _.dropRight() returns a new array and does not modify the original array.
Can _.dropRight() be used with chain syntax in Lodash?
Yes, it can be chained with other Lodash methods for more complex data manipulation sequences.
Conclusion
The _.dropRight() method in Lodash is an efficient solution for trimming arrays from the end. Its ease of use and flexibility make it a key function in various array manipulation tasks in JavaScript. Whether it's processing large datasets or making quick modifications to data, _.dropRight() offers a practical approach to managing array elements.
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.