I have a getSortedIndex function. The function accepts the following arguments:
- An array of objects which are sorted by a key.
- A new object to be inserted into the array.
- The key by which all objects are sorted.
function getSortedIndex(array, objToInsert, key) {
var low = 0,
high = array.length,
value = objToInsert[key];
while (low < high) {
var mid = (low + high) >>> 1;
if (value > array[mid][key]) low = mid + 1;
else high = mid;
}
return low;
}
When the function is called, it returns the index at which the object should be placed into the array:
var sorted_array_of_objects = [
{ 'x': 20 },
// The new object will be placed here.
{ 'x': 30 },
{ 'x': 30 },
{ 'x': 40 },
{ 'x': 50 }
];
var objectToInsert = { 'x': 30, y: 10 };
getSortedIndex(sorted_array_of_objects, objectToInsert, 'x'); //=> 1
My question
Can you modify the function so it returns the index that would place the new object after the objects in the array that have the same value for the x property? If there are no objects in the array with the same value for the x property, then the normal sort index should be returned.
Here's a demo: http://jsbin.com/sortedIndex/3/edit?javascript,console,output
middefined? What's with the;afterwhile (low >> 1?