How to keep Javascript array sorted, without sorting it

后端 未结 3 1850
暖寄归人
暖寄归人 2021-02-04 17:25

I have a Node.js application where I have to very often do following things: - check if particular array already contains certain element - if element does exist, update it - if

3条回答
  •  粉色の甜心
    2021-02-04 18:04

    If your array is already sorted and you want to insert an element, to keep it sorted you need to insert it at a specific place in the array. Luckily arrays have a method that can do that: Array.prototype.splice

    So, once you get the index you need to insert at (you should get by a simple modification to your binary search), you can do:

    myArr.splice(myIndex,0,myObj);
    // myArr your sorted array
    // myIndex the index of the first item larger than the one you want to insert
    // myObj the item you want to insert
    

    EDIT: The author of your binary search code has the same idea:

    So if you wanted to insert a value and wanted to know where you should put it, you could run the function and use the returned number to splice the value into the array. Source

提交回复
热议问题