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();
}