Skip to main content

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"]

Render initial visible items for lazy loading​

Render only the first batch of items eagerly, lazy-load the rest. Essential for fast initial page loads and Core Web Vitals optimization.

const allCards = fetchCards(); // 200 cards
const INITIAL_BATCH = 12;

const eagerCards = take(allCards, INITIAL_BATCH);
const lazyCards = drop(allCards, INITIAL_BATCH);

// Render eager cards immediately
renderCards(eagerCards, { loading: "eager" });

// Lazy-load remaining when they enter viewport
observeIntersection(lazyCards, (card) => renderCard(card, { loading: "lazy" }));

Limit autocomplete suggestions​

Show only the top N matching suggestions in a dropdown. Essential for search autocomplete and combobox components.

const allMatches = searchIndex.filter((item) =>
item.label.toLowerCase().includes(query.toLowerCase())
);

const suggestions = take(allMatches, 8);
// => At most 8 suggestions shown in dropdown

renderDropdown(suggestions);