How to use the nth method in Lodash ?
Last Updated :
23 Apr, 2024
The nth Method in Lodash is used to access elements or characters at specific indices within arrays or strings in JavaScript. You can implement the nth method to perform the below operations in Lodash.
Run the below command before running the code examples on your local machines:
npm i lodash
Use to get an element from an array
In this approach, we are using the nth method with an array to retrieve the element present at the specified index passed as the second argument to the method.
Syntax:
_.nth(array, index);
Example: The below example uses the nth Method to get an element from an array.
JavaScript
const _ = require('lodash');
const array =
["JavaScript", "GFG", 3, 5];
const elementAtIndex2 =
_.nth(array, 1);
console.log(elementAtIndex2);
Output:
GFG
Use to get a character from string
In this approach, we are using Lodash’s nth method with the string and pass an index as the second argument in the same way as we done in the previous implementation to retrieve the character at that index.
Syntax:
_.nth(str, index)
Example: The below example uses the nth Method to get an element from a string.
JavaScript
const _ = require('lodash');
const str = 'Hello, GFG!';
const characterAtIndex7 =
_.nth(str, 7);
console.log(characterAtIndex7);
Output:
G
Share your thoughts in the comments
Please Login to comment...