Chrome Extension

Remove last n elements from an array using Lodash

To remove last n items from an array you can use _.dropRight method if you are using javascript lodash library.
const arr = [1, 2, 3, 4, 5, 6, 7];

//remove last element (n=1) by default
const arr1 = _.dropRight(arr);

//remove last 3 elements
const arr2 = _.dropRight(arr, 3);

//remove last 5 elements
const arr3 = _.dropRight(arr, 5);
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Output
[1,2,3,4,5,6]
[1,2,3,4]
[1,2]

We are removing last n values from array using lodash javascript library. We are using _.dropRight method of lodash to remove array items starting from last. We have defined an array arr which contains 7 values and deleting differnert values using _.dropRight function. If we want to remove last 4 values from arr array constant then we can use below code.

_.dropRight(arr, 4);

_.dropRight lodash

The _.dropRight method of lodash is quite useful when it comes to delete or remove last n elements from the given array. It takes two arguments as parameter. The basic Syntax of this method is below

_.dropRight(Array, N)

Array: This is a required parameter and it is the array which contains all the values along with those values which needs to be removed.

N: This is an optional paramter and it is integer type. The value you pass as N will delete last N items from the given array. The default value of this paraamter is 1 means if you do not pass this parameter value then it will delete last element from the array.

Example Demo:

Search Index Data (The code snippet can also be found with below search text)

_.dropRight lodash
Was this helpful?
0 Comments