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]