简体   繁体   English

javascript:找到正确的索引以将对象放置在对象的排序数组中

[英]javascript: find correct index to place object in sorted array of objects

I have a getSortedIndex function. 我有一个getSortedIndex函数。 The function accepts the following arguments: 该函数接受以下参数:

  1. An array of objects which are sorted by a key. 按键排序的对象数组。
  2. A new object to be inserted into the array. 要插入到数组中的新对象。
  3. 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? 您是否可以修改该函数,以便它返回将新对象放置在数组中具有x属性值的对象之后的索引? If there are no objects in the array with the same value for the x property, then the normal sort index should be returned. 如果数组中没有对象具有x属性的相同值,则应返回常规的排序索引。

Here's a demo: http://jsbin.com/sortedIndex/3/edit?javascript,console,output 这是一个演示: http : //jsbin.com/sortedIndex/3/edit?javascript,控制台,输出

Looks like all you have to do is change the comparison from 看起来您要做的就是将比较从

if (value > array[mid][key])

to

if (value >= array[mid][key])

so that keeps comparing elements with the same value. 这样就可以比较具有相同值的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM