takeWhile()
takeWhile<
T>(array,predicate):T[]
Creates a slice of array with elements taken from the beginning while predicate returns truthy.
Type Parameters
T: T
The type of elements in the array.
Parameters
array: readonly T[]
The array to query.
predicate: (value, index, array) => boolean
The function invoked per iteration.
Returns: T[]
A new array of taken elements.
Since
2.0.0
Performance
O(n) time, stops at first falsy predicate result.
Also known as
takeWhile (Lodash, es-toolkit, Remeda, Ramda, Effect, Modern Dash) · ❌ (Radashi, Antfu)
Example
const users = [
{ user: 'barney', active: true },
{ user: 'fred', active: true },
{ user: 'pebbles', active: false }
];
takeWhile(users, u => u.active);
// => [{ user: 'barney', active: true }, { user: 'fred', active: true }]
takeWhile([1, 2, 3, 4, 5], n => n < 3);
// => [1, 2]
How it works?
Takes elements from the beginning while predicate is true. Stops at first falsy result.
Use Cases
Get leading valid entries 📌
Take elements from the start while they pass a condition. Perfect for extracting prefixes, headers, or valid sequences.
const data = [1, 2, 3, -1, 4, 5];
const validPrefix = takeWhile(data, (n) => n > 0);
// => [1, 2, 3]
Extract consecutive high values
Take leading elements above a threshold. Useful for analyzing initial performance or streak detection.
const scores = [95, 88, 92, 75, 89, 91];
const initialHighScores = takeWhile(scores, (s) => s >= 85);
// => [95, 88, 92]
Get items until condition fails
Extract elements while they match a pattern. Perfect for parsing sequential data or conditional extraction.
const tasks = [
{ status: "done", name: "Task 1" },
{ status: "done", name: "Task 2" },
{ status: "pending", name: "Task 3" },
{ status: "done", name: "Task 4" },
];
const completedPrefix = takeWhile(tasks, (t) => t.status === "done");
// => [Task 1, Task 2]