nth()
nth<
T>(array,index):T|undefined
Gets the element at index n of array.
If n is negative, the nth element from the end is returned. Alias for at.
DEPRECATED
Use array.at(index) directly instead.
Reason:
Alias of at
Type Parametersโ
T: Tโ
The type of elements in the array.
Parametersโ
array: T[]โ
The array to query.
index: numberโ
The index of the element to return.
Returns: T | undefinedโ
The element at the given index, or undefined if out of bounds.
See Alsoโ
Sinceโ
2.0.0
Also known asโ
at (Antfu) ยท get (Effect) ยท nth (Lodash, es-toolkit, Ramda) ยท โ (Remeda, Radashi, Modern Dash)
Exampleโ
const numbers = [1, 2, 3, 4, 5];
// โ Deprecated approach
const last = nth(numbers, -1);
console.log(last); // 5
// โ
Recommended approach
const lastNative = numbers[numbers.length - 1];
console.log(lastNative); // 5
// โ
Modern approach with ES2022
const lastModern = numbers.at(-1);
console.log(lastModern); // 5
How it works?โ
Gets the element at index n.
Deprecated: Use array[n] or array.at(n) directly.
Native Equivalentโ
// โ nth(arr, n)
// โ
arr[n]
// โ
arr.at(n) // ES2022
Use Casesโ
Access element by index ๐โ
Get element at specific index, supporting negative indices.
const items = ['a', 'b', 'c', 'd'];
items[1]; // 'b'
items[items.length - 1]; // 'd' (last)
Get last elementโ
Access last element without knowing array length.
const stack = [1, 2, 3, 4, 5];
const last = stack[stack.length - 1]; // 5