Open In App

Underscore.js _.nth() Method

Improve
Improve
Like Article
Like
Save
Share
Report

The _.nth() method takes an array and an index and hence returns the element on that index in that array.

Syntax:

_.nth(array, index);

Parameters:

  • array: The given array from the element is taken.
  • index: The index on which an element is found.

Return Value: This method returns an element on the given index.

Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed.

underscore.js contrib library can be installed using:

npm install underscore-contrib –save

Example 1: In this example, we will get an element from an array using this method.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [-1, -25, -43, 10, 125, -1];
// Getting nth element
let elem = _.nth(array, 2)
console.log("Original Array : ", array);
console.log("Element: ", elem);


Output:

Original Array :  [ -1, -25, -43, 10, 125, -1 ]
Element:  -43

Example 2: For out of bonds indexes, this method returns undefined.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [-1, -25, -43, 10, 125, -1];
// Getting nth element
let elem = _.nth(array, 100)
console.log("Original Array : ", array);
console.log("Element: ", elem);


Output:

Original Array :  [ -1, -25, -43, 10, 125, -1 ]
Element:  undefined

Example 3: For non-existing negative indexes, this method returns undefined.

javascript




// Defining underscore contrib variable
const _ = require('underscore-contrib');
// Array
let array = [-1, -25, -43, 10, 125, -1];
// Getting nth element
let elem = _.nth(array, -1)
console.log("Original Array : ", array);
console.log("Element: ", elem);


Output:

Original Array :  [ -1, -25, -43, 10, 125, -1 ]
Element:  undefined


Last Updated : 05 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads