Lodash _.sortedIndexBy() Method
Last Updated :
03 Nov, 2023
Lodash _.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 the array to compute their sort ranking. It uses the binary search.
Syntax:
_.sortedIndexBy(array, value, [iteratee=_.identity]);
Parameters:
- 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: In this example, we are getting the index at which we can insert the given value.
Javascript
const _ = require( "lodash" );
let objects = [{ 'x' : 4 }, { 'x' : 6 }];
let index = _.sortedIndexBy(objects,
{ 'x' : 5 }, function (o) { return o.x; });
console.log(index);
|
Output:
1
Example 2: In this example, we are getting the index at which we can insert the given value.
Javascript
const _ = require( "lodash" );
let objects = [{ 'x' : 4 }, { 'x' : 6 }];
let index = _.sortedIndexBy(objects, { 'x' : 9 }, 'x' );
console.log(index);
|
Output:
2
Example 3: In this example, we are getting the index at which we can insert the given value.
Javascript
const _ = require( "lodash" );
let x = [ 'ajax' , 'django' , 'mongoDb' ,
'react' , 'reactnative' , 'yarn' ]
let index = _.sortedIndexBy(x, 'luby' , 5);
console.log(index);
|
Output:
3
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
Share your thoughts in the comments
Please Login to comment...