Lodash | _.nth() Method

The _.nth() method is used to return the nth index of the element. For a negative value of n, it returns the nth element from the end.

Syntax:

_.nth(array, n)

Parameters: This method accepts two parameters as mentioned above and described below:

  • Array: This parameter holds the query array.
  • n: This parameter holds the index of element that to be extracted.

Return Value: It returns the nth element of the array.

Example 1: It returns the third element of an array.



filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
let ar = [1, 2, 3, 4, 5]
  
let value = _.nth(ar, 3)
  
console.log(value)

chevron_right


Here, const _ = require('lodash') is used to import the lodash library into the file.

Output:

4

Example 2: It returns the third element from the end of an array because the value of n is negative.

filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
let ar = [1, 2, 3, 4, 5]
  
let value = _.nth(ar, -3)
  
console.log(value)

chevron_right


Output:

3

Example 3: It returns undefined because there is no element at index 8.

filter_none

edit
close

play_arrow

link
brightness_4
code

const _ = require('lodash');
  
let ar = [1, 2, 3, 4, 5]
  
let value = _.nth(ar, 8)
  
console.log(value)

chevron_right


Output:

undefined

Reference: https://lodash.com/docs/4.17.15#nth

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.