takeWhileLoading saved progress…

takeWhile

take and takeWhile grab elements from the front of an array. take returns the first n; takeWhile returns the leading run of elements that pass a test and stops at the first one that fails. They're the mirror image of drop/dropWhile, which discard from the front instead of keeping.

Implement both. take(arr, n) returns the first n elements (default 1, clamped to the array's bounds). takeWhile(arr, predicate) returns the longest prefix where predicate is truthy — the moment it fails, you stop, even if later elements would pass.

Signature

function take(arr, n = 1) { /* first n elements as a new array */ }
function takeWhile(arr, predicate) { /* leading run where predicate is truthy */ }

Examples

take([1, 2, 3, 4], 2); // [1, 2]
take([1, 2, 3]);       // [1]  — n defaults to 1
take([1, 2], 10);      // [1, 2] — clamped to the length
takeWhile([1, 2, 3, 4], (n) => n < 3);  // [1, 2]
takeWhile([1, 2, -1, 3], (n) => n > 0); // [1, 2] — stops at -1, ignores the later 3

Notes

  • take default is 1take(arr) returns the first element in an array.
  • take clampsn <= 0 gives []; n beyond the length gives a full copy.
  • takeWhile stops at the first failure — it returns a prefix, not every matching element. A later passing element after a failure is not included.
  • Predicate argumentstakeWhile calls predicate(value, index, array).
  • New array, no mutation — both return a fresh array and leave the input alone.
Loading editor…