Aller au contenu principal

at()

at<T>(arr, index): T | undefined

Returns the item at the given index, allowing for positive and negative integers.

Negative integers count back from the last item in the array.

DEPRECATED

Use array.at(index) directly instead.

Reason:
Native equivalent method now available


Type Parameters

T: T

The type of elements in the array.


Parameters

arr: 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 (Lodash, es-toolkit, Antfu) · get (Effect) · nth (Ramda) · ❌ (Remeda, Radashi, Modern Dash)


Example

const numbers = [1, 2, 3, 4, 5];

// ❌ Deprecated approach
const first = at(numbers, 0);
console.log(first); // 1

const last = at(numbers, -1);
console.log(last); // 5

// ✅ Recommended approach
const firstNative = numbers[0];
console.log(firstNative); // 1

const lastNative = numbers[numbers.length - 1];
console.log(lastNative); // 5

// ✅ Modern approach with ES2022
const firstModern = numbers.at(0);
console.log(firstModern); // 1

const lastModern = numbers.at(-1);
console.log(lastModern); // 5

How it works?

Returns the item at the given index, supporting negative indices. Deprecated: Use array.at(index) directly (ES2022).

Negative Index

Native Equivalent

// ❌ at(arr, -1)
// ✅ arr.at(-1)

Use Cases

Access array elements with negative indices 📌

Retrieve elements from the end of an array using negative indices.

const history = ["page1", "page2", "page3", "page4", "page5"];
history.at(-1); // => "page5"
history.at(-2); // => "page4"

Access step in multi-step wizard

Get the current step data based on a dynamic step index.

const wizardSteps = [{ id: "personal" }, { id: "address" }, { id: "payment" }];
wizardSteps[currentStepIndex];
// => { id: "payment" }

Get slides relative to current position for navigation.

const slides = ["intro", "features", "pricing", "contact"];
slides[currentIndex + 1]; // next
slides[currentIndex - 1]; // prev