Skip to main content

take

Returns a new array containing the first n elements of the array.

If no additional argument is provided, returns a new array containing only the first element.

If the count to take is greater than the array length, returns the entire array.

If the count to take is negative, returns an empty array.


Code

🔗 View source code


Benchmark

  • hz: Operations per second
  • mean: Average response time (ms)
NamehzmeanPerformance
modern-kit/take6,771,043.430.0001fastest
lodash/take2,601,105.350.0004slowest
  • modern-kit/take
    • 2.60x faster than lodash/take

Interface

typescript
function take<T>(arr: T[] | readonly T[], count: number = 1): T[]

Usage

typescript
import { take } from '@modern-kit/utils';

const arr = [1, 2, 3, 4, 5];
console.log(take(arr)); // [1]
console.log(take(arr, 0)); // []
console.log(take(arr, 2)); // [1, 2]
console.log(take(arr, 7)); // [1, 2, 3, 4, 5]