简体   繁体   中英

How to sort array as items as added in Javascript?

I have an array of objects, whose elements as displayed using ng-repeat from AngularJS. Each object has a priority_int integer value, and I know that I can sort the array is descending order with:

array.sort(function(a,b){
    return b.priority_int - a.priority_int;
}

Currently, I'm adding everything to the array, before sorting by priority_int in descending order, and then displaying with ng-repeat.

Out of curiousity, how can I sort every time I push an object into the array?

Resorting the array each time you add an element will cost a heavy runtime penalty, especially since some default array.sort implementations have an O(n^2) runtime for a nearly-sorted array.

Instead, use binary search to insert new elements into the correct position in the sorted array.

Check this related answer for more help:

Efficient way to insert a number into a sorted array of numbers?

The easiest way to do this would be to first find the index of where the new element should be placed. Then, you should add the element there.

var addToReverseSortedArray = function (arr, item) {
    // our function to find the index of an element
    // (or where it should be placed)
    var search = function (a, i) {
        var low = 0, high = a.length - 1;
        while (low <= high) {
            var mid = (low + high) >> 1;
            if (a[mid] > i) low = mid + 1;
            else if (a[mid] < i) high = mid - 1;
            else return mid;
        }
        return low;
    }
    // Array.splice can actually splice 0 items
    // here, we splice 0 items at index search(arr, item)
    // and add `item`
    arr.splice(search(arr, item), 0, item);
    return arr;
}

Mind you, the above function relies on an array in reverse sorted order.

Examples:

addToReverseSortedArray([5,4,3], 6); // [6,5,4,3]
addToReverseSortedArray([1,0,0,0], 10); // [10,1,0,0,0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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