Lodash _.sortedIndexBy() Method

The _.sortedIndexBy() method is used to return the lowest index of the array where an element can be inserted and maintain its sorted order. In addition, it accepts iteratee which is invoked for value and each element of array to compute their sort ranking.It uses the binary search.
Syntax:
_.sortedIndexBy(array, value, [iteratee=_.identity])
Parameters: This method accepts three parameters as mentioned above and described below:
- array: This parameter holds the sorted array.
- value: This parameter holds the value to evaluate.
- Iteratee: This is the function that iterates over each element.
Return Value: This method returns the index at which the value should be inserted into the array.
Example 1: Here, const _ = require(ālodashā) is used to import the lodash library into the file.
Javascript
// Requiring the lodash libraryĀ const _ = require("lodash");Ā Ā Ā Ā Ā // Original arrayĀ var objects = [{ 'x': 4 }, { 'x': 6 }]; Ā Ā Ā Ā // Use of _.sortedIndexBy()Ā // methodĀ let index = _.sortedIndexBy(objects,Ā Ā Ā Ā Ā { 'x': 5 }, function(o) { return o.x; }); Ā Ā Ā Ā // Printing the outputĀ console.log(index); |
Output:
1
Example 2:
Javascript
// Requiring the lodash libraryĀ const _ = require("lodash");Ā Ā Ā Ā Ā // Original arrayĀ var objects = [{ 'x': 4 }, { 'x': 6 }]; Ā Ā Ā Ā // Use of _.sortedIndexBy()Ā // methodĀ let index = _.sortedIndexBy(objects, { 'x': 9 }, 'x'); Ā Ā Ā Ā // Printing the outputĀ console.log(index); |
Output:
2
Example 3:
Javascript
// Requiring the lodash libraryĀ const _ = require("lodash");Ā Ā Ā Ā Ā // Original arrayĀ let x = ['ajax', 'django', 'mongoDb',Ā Ā Ā Ā Ā Ā Ā Ā Ā 'react', 'reactnative', 'yarn']Ā Ā Ā Ā Ā Ā // Use of _.sortedIndexBy()Ā // methodĀ let index = _.sortedIndexBy(x, 'luby', 5); Ā Ā Ā Ā // Printing the outputĀ console.log(index); |
Output:
3
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.


