take()
take<
T>(array,count):T[]
Creates a slice of array with n elements taken from the beginning.
Type Parametersโ
T: Tโ
The type of elements in the array.
Parametersโ
array: readonly T[]โ
The array to query.
count: numberโ
The number of elements to take.
Returns: T[]โ
A new array with the first count elements.
Throwsโ
RangeError If count is negative.
Sinceโ
2.0.0
Also known asโ
take (Lodash, es-toolkit, Remeda, Ramda, Effect, Modern Dash) ยท โ (Radashi, Antfu)
Exampleโ
const numbers = [1, 2, 3, 4, 5];
take(numbers, 3);
// => [1, 2, 3]
take(numbers, 0);
// => []
take(numbers, 10);
// => [1, 2, 3, 4, 5]
How it works?โ
Use Casesโ
Limit results to first N items ๐โ
Get the first N elements from an array. Essential for "Top 10" lists, previews, or limiting API responses.
const allProducts = [
{ name: "Laptop", sales: 1500 },
{ name: "Phone", sales: 3200 },
{ name: "Tablet", sales: 800 },
{ name: "Watch", sales: 2100 },
{ name: "Headphones", sales: 1800 },
];
const topThree = take(allProducts, 3);
// => [Laptop, Phone, Tablet]
Preview content without loading everythingโ
Show a preview of items before revealing the full list. Perfect for "Show more" patterns or lazy loading.
const notifications = [
{ id: 1, message: "New comment on your post" },
{ id: 2, message: "You have a new follower" },
{ id: 3, message: "Your order shipped" },
{ id: 4, message: "Password changed" },
{ id: 5, message: "New message received" },
];
const preview = take(notifications, 3);
// => First 3 notifications
// Show "See 2 more" button
Get first page of dataโ
Extract the first batch for initial page load. Useful for pagination or infinite scroll initialization.
const allItems = Array.from({ length: 100 }, (_, i) => `Item ${i + 1}`);
const pageSize = 20;
const firstPage = take(allItems, pageSize);
// => ["Item 1", "Item 2", ..., "Item 20"]