【问题标题】:Insert json object to ordered array in javascript在javascript中将json对象插入有序数组
【发布时间】:2016-07-17 07:31:55
【问题描述】:

我有一个大约 2000 个对象的数组,格式如下:

[{
    "$order": 2998,
    "text": "Rosales Glenn",
    "id": 375
}, {
    "$order": 2999,
    "text": "Dillard Joyce",
    "id": 450
}, {
    "$order": 3000,
    "text": "Maryellen Hogan",
    "id": 365
}, {
    "$order": 3002,
    "text": "Jeannette Church",
    "id": 207
}]

我需要以有效的方式将对象插入正确的位置: 例如:

{
    "$order": 3001,
    "text": "Jeannette Chichi",
    "id": 205
}

假设我在插入新元素时不需要覆盖现有元素(没有重复的“$order”),有人知道使用 $order 作为键将新对象插入到数组中的快速算法吗? 外部库也是一种选择(如果它们支持 Angular)。 谢谢!

【问题讨论】:

  • 如果数组以 $order = 3002.... 开头则不起作用。

标签: javascript arrays json sorting


【解决方案1】:

至少你需要迭代直到找到索引。

var array = [{ "$order": 2998, "text": "Rosales Glenn", "id": 375 }, { "$order": 2999, "text": "Dillard Joyce", "id": 450 }, { "$order": 3000, "text": "Maryellen Hogan", "id": 365 }, { "$order": 3002, "text": "Jeannette Church", "id": 207 }],
    insert = { "$order": 3001, "text": "Jeannette Chichi", "id": 205 },
    index = -1;

array.some(function (a,i) {
    if (a.$order > insert.$order) {
        return true;
    }
    index = i;
});

array.splice(index + 1, 0, insert);

console.log(array);

或者按照建议,您可以使用二进制搜索。

function search(array, insert, cb) {
    var left = -1,
        right = array.length,
        actual;

    while (left !== right && left + 1 !== right) {
        actual = Math.floor((left + right) / 2);
        if (cb(array[actual]) < cb(insert)) {
            left = actual;
            continue;
        }
        if (cb(array[actual]) > cb(insert)) {
            right = actual;
        }
    }
    return left;
}

var array = [{ "$order": 2998, "text": "Rosales Glenn", "id": 375 }, { "$order": 2999, "text": "Dillard Joyce", "id": 450 }, { "$order": 3000, "text": "Maryellen Hogan", "id": 365 }, { "$order": 3002, "text": "Jeannette Church", "id": 207 }],
    insert = { "$order": 3001, "text": "Jeannette Chichi", "id": 205 },
    index = search(array, insert, function (a) { return a.$order; });

array.splice(index + 1, 0, insert);
console.log(array);

【讨论】:

    【解决方案2】:

    看起来你不能低于拼接实现的复杂性,这取决于引擎。

    您可以优化的是您的搜索算法。我会去二进制搜索。

    编辑有关二分搜索的更多信息,请参阅http://www.tutorialspoint.com/data_structures_algorithms/binary_search_algorithm.htm

    【讨论】:

      猜你喜欢
      • 2018-06-03
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多