Array/Since
1.38.0take
Returns a new array containing the first n elements of the input array.
take(array, n):T[]Parameters
arrayT[]requiredThe array from which elements should be taken.
nnumberrequiredThe number of elements to take from the beginning of the array.
Returns
T[]A new array containing the first n elements of the input array.
Examples
01
Basic usage
Take the first three elements from an array.
TypeScript
import { take } from "@cyref/js";
const numbers = [1, 2, 3, 4, 5];
const result = take(numbers, 3);
console.log(result);
// [1, 2, 3]02
Taking more than the array length
If n is greater than or equal to the array length, a copy of the entire array is returned.
TypeScript
import { take } from "@cyref/js";
const numbers = [1, 2, 3];
const result = take(numbers, 10);
console.log(result);
// [1, 2, 3]03
Zero or negative n
When n is zero or negative, the function returns an empty array.
TypeScript
import { take } from "@cyref/js";
const numbers = [1, 2, 3, 4, 5];
console.log(take(numbers, 0));
// []
console.log(take(numbers, -2));
// []04
Taking all elements
When n equals the array length, all elements are returned in a new array.
TypeScript
import { take } from "@cyref/js";
const numbers = [1, 2, 3];
const result = take(numbers, numbers.length);
console.log(result);
// [1, 2, 3]05
Empty array
Taking elements from an empty array returns an empty array.
TypeScript
import { take } from "@cyref/js";
const result = take([], 3);
console.log(result);
// []Built with@cyref/js·Official documentation