Lodash _.sortedIndexOf() Method
Lodash _.sortedIndexOf() method is used to get the index of the first occurrence of the particular element in the sorted array. It uses the binary search to sort an array.
Syntax:
_.sortedIndexOf(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, other returns -1.
Example 1: In this example, we are getting the index at which we got the given value in the given array.
Javascript
const _ = require( "lodash" );
let x = [1, 2, 3, 4, 4, 4, 5, 6, 6]
let index = _.sortedIndexOf(x, 4);
console.log(index);
|
Output:
3
Example 2:In this example, we are getting the index at which we got the given value in the given array.
Javascript
const _ = require( "lodash" );
let x = [ 'a' , 'b' , 'c' , 'd' , 'e' , 'e' , 'e' , 'f' ]
let index = _.sortedIndexOf(x, 'e' );
console.log(index);
|
Output:
4
Example 3: In this example, we are getting -1 as the index because the given value is not present in the given array.
Javascript
const _ = require( "lodash" );
let x = [ 'ajax' , 'django' , 'mongoDb' ,
'react' , 'reactnative' , 'yarn' ]
let index = _.sortedIndexOf(x, 'luby' );
console.log(index);
|
Output:
-1
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.
Last Updated :
03 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...