Skip to main content

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