Files
30-seconds-of-code/snippets/nth-element.md
Stefan Feješ b848906fe5 fix naming
2017-12-17 15:41:31 +01:00

372 B

Nth element of array

Use Array.slice() to get an array containing the nth element at the first place. If the index is out of bounds, return []. Omit the second argument, n, to get the first element of the array.

const nthElement = (arr, n=0) => (n>0? arr.slice(n,n+1) : arr.slice(n))[0];
// nth(['a','b','c'],1) -> 'b'
// nth(['a','b','b']-2) -> 'a'