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