要做到這一點最簡單的方法是首先找到其中的新元素應該放在索引。然後,你應該在那裏添加元素。
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;
}
請注意,上面的函數依賴於逆序排列的數組。
例子:
addToReverseSortedArray([5,4,3], 6); // [6,5,4,3]
addToReverseSortedArray([1,0,0,0], 10); // [10,1,0,0,0]
創建一個函數,它的值,然後推動它和排序,並使用你的推? – 2015-02-24 21:19:28
你可以用'ng-repeat'進行排序 – 2015-02-24 21:22:36