Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

lodash
nth
array
communitycreator

How to use the "nth" method in Lodash

Programming Bytes

Overview

The nth method can be used to get the element at a specific element.

Syntax

_.nth(array, [n=0])

Paramater

This method takes two arguments.

  • array: The array from which elements are taken.
  • n: Index of the element to be taken. It is an optional argument. The default value is 0 (returns the first element). If we pass a negative value then the element is taken from the end of the array.

Return value

This method returns the array element at the provided index. If the index is out of range then undefined is returned.

Example

The below code demonstrates how to use the nth method in Lodash:

Console
Using the "nth" method

Explanation

In the above code,

  • Line 6: We load the Lodash library file from the server link.

  • Line 8: We create an array arr with [1,2,3,4,5] as elements.

  • Line 12: We use the nth method to get the array, 2nd element of the index. This returns 3 as result.

  • Line 15: We use the nth method to get the array element at the -1st index. For the negative index, the elements are taken from the end of the array. We get 5 as a result because index -1 denotes the last element of the array.

  • Line 18: We use the nth method to get the array element at the 10th index. There is no element present in the provided index, so undefined is returned.

RELATED TAGS

lodash
nth
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring