Aller au contenu principal

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