Skip to main content

takeRight()

takeRight<T>(array, count): T[]

Creates a slice of array with n elements taken from the end.


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 last count elements.


Throws​

RangeError If count is negative.


Since​

2.0.0


Also known as​

takeLast (Remeda, Ramda) · takeRight (Lodash, es-toolkit, Effect, Modern Dash) · ❌ (Radashi, Antfu)


Example​

const numbers = [1, 2, 3, 4, 5];

takeRight(numbers, 3);
// => [3, 4, 5]

takeRight(numbers, 0);
// => []

How it works?​

Takes elements from the end instead of the beginning.


Use Cases​

Show recent activity in dashboards πŸ“Œβ€‹

Display the last N actions for quick context. Perfect for "Recent Files", "Last Commands", or activity feeds.

const auditLog = [
"User login",
"File uploaded",
"Settings changed",
"Report generated",
"User logout",
];

const recentActions = takeRight(auditLog, 3);
// => ["Settings changed", "Report generated", "User logout"]

Extract trailing data points for trend analysis​

Get the most recent values for sparklines or mini-charts. Ideal for dashboards, stock tickers, or performance monitors.

const cpuHistory = [45, 52, 48, 67, 72, 68, 71, 85, 82, 79];

const recentTrend = takeRight(cpuHistory, 4);
// => [71, 85, 82, 79]

const isIncreasing = recentTrend[3] > recentTrend[0];
// => true (trending up)

Get last page of paginated data​

Extract the final batch when you know total count. Useful for "Jump to last page" functionality.

const allItems = Array.from({ length: 47 }, (_, i) => `Item ${i + 1}`);
const pageSize = 10;

const lastPage = takeRight(allItems, 47 % pageSize || pageSize);
// => ["Item 41", "Item 42", ..., "Item 47"]

Show recent chat messages on reconnect​

Display the last N messages when a user reconnects to a chat room. Essential for messaging apps and real-time collaboration tools.

const chatHistory = await fetchChatHistory(roomId);

// Show last 50 messages on reconnect
const recentMessages = takeRight(chatHistory, 50);
renderMessages(recentMessages);

// Show "Load earlier messages" button if there are more
if (chatHistory.length > 50) {
showLoadEarlierButton();
}