Files
30-seconds-of-code/snippets/js/s/nth-element.md
Angelos Chalaris 4d0316a062 Update covers
2023-05-07 22:25:00 +03:00

590 B

title, type, language, tags, cover, dateModified
title type language tags cover dateModified
Nth element snippet javascript
array
rocky-mountains-2 2020-10-21T21:54:53+03:00

Returns the nth element of an array.

  • Use Array.prototype.slice() to get an array containing the nth element at the first place.
  • If the index is out of bounds, return undefined.
  • Omit the second argument, n, to get the first element of the array.
const nthElement = (arr, n = 0) =>
  (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];
nthElement(['a', 'b', 'c'], 1); // 'b'
nthElement(['a', 'b', 'b'], -3); // 'a'