Skip to content

take

Import from @varavel/vdl-plugin-sdk/utils/arrays.

function take<T>(
   arr, 
   count?, 
   guard?): T[];

Returns a new array containing the first count elements from the input array arr. If count is greater than the length of arr, the entire array is returned.

Type Parameters

Type Parameter Description
T Type of elements in the input array.

Parameters

Parameter Type Description
arr readonly T[] The array to take elements from.
count? number The number of elements to take.
guard? unknown If truthy, ignores count and defaults to 1.

Returns

T[]

A new array containing the first count elements from arr.

Examples

// Returns [1, 2, 3]
take([1, 2, 3, 4, 5], 3);
// Returns ['a', 'b']
take(['a', 'b', 'c'], 2);
// Returns [1, 2, 3]
take([1, 2, 3], 5);
// Returns [[1], [1], [1]]
const arr = [1, 2, 3];
const result = arr.map((v, i, array) => take(array, i, true));