Say I have an array already with these articles, ordered by lowest to highest price:
[
{ title: "Article 3", price: 1.49 },
{ title: "Article 1", price: 3.00 },
{ title: "Article 4", price: 5.99 },
{ title: "Article 2", price: 19.99 }
]
Basically I would like to push another article into the array at the correct position (by price). How can I do so?
The new article I'm pushing may have the following properties:
{ title: "Article 5", price: 12.00 }
I'm expecting the article to appear at index 3 (between article 4 and 2).
UPDATE (SOLUTION)
I created a prototype method using @klutt's answer with binary search algorithm:
Array.prototype.pushSorted = function(el, compareFn) {
this.splice((function(arr) {
var m = 0;
var n = arr.length - 1;
while(m <= n) {
var k = (n + m) >> 1;
var cmp = compareFn(el, arr[k]);
if(cmp > 0) m = k + 1;
else if(cmp < 0) n = k - 1;
else return k;
}
return -m - 1;
})(this), 0, el);
return this.length;
};
const sortByPrice = (a, b) => a.price > b.price;
theArray.pushSorted({ title: "Article 5", price: 12.00 }, sortByPrice);