Lodash _.takeWhile() Method
Last Updated :
30 Oct, 2023
Lodash _.taketWhile the method is used to create a slice of an array in which elements are taken from the beginning. Also, these elements are taken until the predicate returns falsely.
Syntax:
_.takeWhile(array, [predicate=_.identity]);
Parameters:
- array: This parameter holds the array to query.
- [predicate=_.identity]: This parameter holds the function invoked per iteration.
Return Value:
This method is used to return the slice of the array.
Example 1: In this example, it is returning the two objects of an array as the third one is returning false.
javascript
const _ = require( "lodash" );
let users = [
{ 'user' : 'jupiter' , 'active' : false },
{ 'user' : 'mercury' , 'active' : false },
{ 'user' : 'saturn' , 'active' : true }
];
let gfg = _.takeWhile(users, function (o) { return !o.active; });
console.log(gfg);
|
Output:
[{ user: 'jupiter', active: false },
{user: 'mercury', active: false}]
Example 2: In this example, it is returning the one object of an array as the second one is returning false.
javascript
const _ = require( "lodash" );
let users = [
{ 'user' : 'jupiter' , 'active' : false },
{ 'user' : 'mercury' , 'active' : false },
{ 'user' : 'saturn' , 'active' : true }
];
let gfg = _.takeWhile(users, { 'user' : 'jupiter' , 'active' : false });
console.log(gfg);
|
Output:
[{ user: 'jupiter', active: false }]
Example 3: In this example, it is returning the two objects of an array as the third one is returning false.
javascript
const _ = require( "lodash" );
let users = [
{ 'user' : 'jupiter' , 'active' : false },
{ 'user' : 'mercury' , 'active' : false },
{ 'user' : 'saturn' , 'active' : true }
];
let gfg = _.takeWhile(users, [ 'active' , false ]);
console.log(gfg);
|
Output:
[{ user: 'jupiter', active: false },
{user: 'mercury', active: false}]
Example 4: In this example, it is returning empty array as first one is returning false so it will not check further.
javascript
const _ = require( "lodash" );
let users = [
{ 'user' : 'jupiter' , 'active' : false },
{ 'user' : 'mercury' , 'active' : false },
{ 'user' : 'saturn' , 'active' : true }
];
let gfg = _.takeWhile(users, 'active' );
console.log(gfg);
|
Output:
[]
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...