Design & Download
Your JS Library
in Seconds!!!

Snippet: nth() - nth Element In An Array

Written by Christopher West (cwest) on December 04, 2015.
Gets the nth value within an array or an array-like object. A negative n (index) means that it will be counted from the end to the beginning.
function nth(arr, n) {
  return arr[n < 0 ? arr.length + n : n];
}

nth(...) API Documentation

Gets the nth value within an array or an array-like object. A negative n (index) means that it will be counted from the end oto the beginning.

Parameters

  1. arr {Array|Object}:
    The array or array-like object from which a value will be returned.
  2. n {number}:
    The index of the value to get. If negative, the index will be counted from the end of arr.

Returns

The value found at the specified index (n).