Open In App

Lodash _.sortedIndex() Method

Last Updated : 02 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Lodash _.sortedIndex() method is used to return the lowest index of the array where an element can be inserted and maintain its sorted order. It uses the binary search.

Syntax:

_.sortedIndex(array, value);

Parameters:

  • array: This parameter holds the sorted array.
  • value: This parameter holds the value to evaluate.

Return Value:

  • This method returns the index at which the value should be inserted into the array.

Example 1: In this example, we are getting the index number of the given value at which we can insert that value into the given array.

JavaScript
// Requiring the lodash library 
const _ = require("lodash");

// Original array 
let x = [1, 2, 3, 4, 4, 4, 5, 6, 6]

// Use of _.sortedIndex() 
// method 
let index = _.sortedIndex(x, 4);

// Printing the output 
console.log(index); 

Output:

3

Example 2: In this example, we are getting the index number of the given value at which we can insert that value into the given array.

JavaScript
// Requiring the lodash library 
const _ = require("lodash");

// Original array 
let x = ['a', 'b', 'c', 'd', 'e', 'e', 'e', 'f']

// Use of _.sortedIndex() 
// method 
let index = _.sortedIndex(x, 'e');

// Printing the output 
console.log(index); 

Output:

4

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


Similar Reads