Menu

gitpiper

nthElement javascript Code Snippet in 2024

arraybeginner

Last Updated: 1 December 2024

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'

javascript snippet similar to nthElement For You in December 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️