Lodash is a modern and one of the most popular JavaScript libraries, with more than two hundred functions geared towards reducing the work involved in web development.
This library features helper functions like filtering, templating, deep equality checks`, mapping, creating indexes, etc.
This Answer will discuss the dropRightWhile()
function mainly used when working with arrays.
Let's understand how to implement the dropRightWhile()
function in Lodash.
output_array = _.dropRightWhile(input_array, [predicate=_.identity])
When invoked, this function creates a sliced copy of the input array, excluding the elements that dropped from its end. The array elements are dropped until the predicate function returns false.
This function takes the following arguments:
input_array
: This is the source array that we want to process. The method will iterate over its elements from the end to the beginning.
predicate
: A function loops over the input array elements from the end to the beginning while evaluating a prespecified condition to either true or false.
Let's look at the following example to gain a better understanding of how this function works:
Within this example, we will define an array storing some employees' information, and we will try to remove from the end of this array the elements having a salary <= 1000
while using the function dropRightWhile
:
const _ = require("lodash");let employeesArray = [{ name: "Bassem" , Salary:900 },{ name: "Celeste", Salary:300 },{ name: "Cindi" , Salary:750 },{ name: "Rachel" , Salary:500 }]let outputArray = _.dropRightWhile(employeesArray, (e) => {if (e.Salary > 1000) {return false}return true});console.log("original Employees Array:")console.log(employeesArray)console.log("Generated Array:")console.log(outputArray)
Let's go through the code widget above:
Line 1: Load the Lodash JavaScript library.
Lines 3–8: Define an array storing the employees' information. This array will mainly include two attributes: the employee's name and salary.
Lines 10–15: Invoke the function dropRightWhile
while specifying as a condition: e.Salary > 1000
. This function will iterate over each element of the employeesArray
starting from the last element of this array and will drop the elements not respecting the previously mentioned condition.
Lines 17–18: Display the original array.
Lines 20–21: Print out the resulting sliced array.
Free Resources