Removing array items from START until given condition is false using Lodash

In today’s article of Lodash, we will learn about how to remove elements from the beginning until a specified condition is not satisfied in an array. To do so we can use dropWhile function of Lodash library in JavaScript.

About Lodash’s _.dropWhile() Method

The dropWhile function is used to return the slice out the value from the given array. This function will visit all the elements of the array and if this function returns the false value based on the condition, then function will return the array elements excluding elements from the beginning until the given condition is satisfied.

Syntax

dropWhile(array, [predicate=_.identity])

First parameter is array which needs to be sliced and the second argument will be the function that either returns true or false depending on the condition given.

Code

// Requiring the Lodash library
const _ = require("lodash");

var users = [
    { 'user': 'Ankit', 'active': false },
    { 'user': 'John', 'active': true },
    { 'user': 'Deo', 'active': false }
];

const result = _.dropWhile(users, function (o) {
    return !o.active;
});
console.log(result);

Output

[
    { 'user': 'John', 'active': true },
    { 'user': 'Deo', 'active': false }
];

1 thought on “Removing array items from START until given condition is false using Lodash”

Leave a Comment