Skip to main content

at

Returns an element at a specific index from the given array.

Array.prototype.at() is a modern spec function, so this utility can be used when browser compatibility issues arise.


Code

🔗 View source code


Benchmark

  • hz: Operations per second
  • mean: Average response time (ms)
NamehzmeanPerformance
modern-kit/at5,830,795.680.0003fastest
lodash/nth1,801,680.740.0005slowest
  • modern-kit/at
    • 3.24x faster than lodash/nth

Interface

typescript
function at<T>(arr: T[] | readonly T[], index: number = 0): T | undefined

Usage

Positive index

typescript
import { at } from '@modern-kit/utils';

at([1, 2, 3, 4, 5]); // 1
at([1, 2, 3, 4, 5], 0); // 1
at([1, 2, 3, 4, 5], 1); // 2
at([1, 2, 3, 4, 5], 2); // 3

Negative index

typescript
import { at } from '@modern-kit/utils';

at([1, 2, 3, 4, 5], -1); // 5
at([1, 2, 3, 4, 5], -2); // 4
at([1, 2, 3, 4, 5], -3); // 3

Out-of-range index

typescript
import { at } from '@modern-kit/utils';

at([1, 2, 3, 4, 5], 3); // undefined
at([1, 2, 3, 4, 5], -4); // undefined