Last Updated : 02 Sep, 2024
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:
Example 1: In this example, it is returning the two objects of an array as the third one is returning false.
javascript
// Requiring the lodash library
const _ = require("lodash");
// Original array
let users = [
{ 'user': 'jupiter', 'active': false },
{ 'user': 'mercury', 'active': false },
{ 'user': 'saturn', 'active': true }
];
// Use of _.takeWhile()
// method
let gfg = _.takeWhile(users, function (o) { return !o.active; });
// Printing the output
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
// Requiring the lodash library
const _ = require("lodash");
// Original array
let users = [
{ 'user': 'jupiter', 'active': false },
{ 'user': 'mercury', 'active': false },
{ 'user': 'saturn', 'active': true }
];
// Use of _.takeWhile()
// method
// The `_.matches` iteratee shorthand.
let gfg = _.takeWhile(users, { 'user': 'jupiter', 'active': false });
// Printing the output
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
// Requiring the lodash library
const _ = require("lodash");
// Original array
let users = [
{ 'user': 'jupiter', 'active': false },
{ 'user': 'mercury', 'active': false },
{ 'user': 'saturn', 'active': true }
];
// Use of _.takeWhile()
// method
// The `_.matchesProperty` iteratee shorthand.
let gfg = _.takeWhile(users, ['active', false]);
// Printing the output
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
// Requiring the lodash library
const _ = require("lodash");
// Original array
let users = [
{ 'user': 'jupiter', 'active': false },
{ 'user': 'mercury', 'active': false },
{ 'user': 'saturn', 'active': true }
];
// Use of _.takeWhile()
// method
// The `_.property` iteratee shorthand.
let gfg = _.takeWhile(users, 'active');
// Printing the output
console.log(gfg);
Output:
[]
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4