Array
take

🍴 Takes a specified number of elements from the start of an array.

It is loosely based on the Iterator.prototype.take() (opens in a new tab) method.

Syntax

import { take } from '@opentf/std';
 
take<T>(
  arr: T[],
  limit: number | null = 1,
  cb?: (val: T) => boolean
): T[]

Parameters

  • arr: The source array.
  • limit: The number of elements to take. If null, all elements are taken.
  • cb: An optional predicate function. If provided, only elements that return true are taken, up to the limit.

Returns

A new array containing the taken elements.

Examples

take([1, 2, 3], -1) // Throws RangeError for negative limit
 
take([1, 2, 3], 0) //=> []
 
take([1, 2, 3]) //=> [1]
 
take([1, 2, 3], 1) //=> [1]
 
take([1, 2, 3], 2) //=> [1, 2]
 
take([1, 2, 3, 4, 5], 5) //=> [1, 2, 3, 4, 5]
 
take([1, 2, 3, 4, 5], 6) //=> [1, 2, 3, 4, 5]
 
take([1, 2, 3, 4, 5], null) //=> [1, 2, 3, 4, 5]
 
take([1, 2, 3, 4, 5], 2, (val) => val % 2 === 0) //=> [2, 4]
 
take([1, 2, 3, 4, 5], 3, (val) => val % 2 !== 0) //=> [1, 3, 5]
 
const users = [
  { name: 'x', active: false },
  { name: 'y', active: true },
  { name: 'z', active: false },
];
take(users, null, (val) => val.active) 
//=> [
//   { name: 'y', active: true },
// ]

Related

Try