Underscore.JS - sortedIndexOf method



Syntax

_.sortedIndex(array, value, [iteratee], [context])

sortedIndex method uses a binary search to insert an value in array to maintain sort order and returns index. If an iteratee function is present, than that will be used to compute the index.

Example

var _ = require('underscore');

var list = [1, 2, 4, 5, 6]
//Example: get sorted index of 3
result = _.sortedIndex(list, 3);
console.log(result)

list = [{name: 'Joe', age: 40}, {name: 'Rob', age: 60}];
//Example: get sorted index of new object
result = _.sortedIndex(list, {name: 'Julie', age: 50}, 'age' );
console.log(result)

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

2
1
underscorejs_iterating_array.htm
Advertisements