How to keep Javascript array sorted, without sorting it

后端 未结 3 1853
暖寄归人
暖寄归人 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:11

    I know this is an answer to an old question, but the following is very simple using javascripts array.splice().

    function inOrder(arr, item) {
        /* Insert item into arr keeping low to high order */
    
        let ix = 0;
        while (ix < arr.length) {
            //console.log('ix',ix);
            if (item < arr[ix]) { break; }
            ix++;
        }
    
        //console.log('  insert:', item, 'at:',ix);
        arr.splice(ix,0,item);
        return arr
    }
    

    The order can be changed to high to low by inverting the test

提交回复
热议问题