javascript sort and sort equals on result. how?
javascript, sorting
Solution
To make you sort stable, you will need to compare the "equal" items by their index:
// mass = [{name:…, count:…}, {name:…, count:…}, …]
for (var i=0; i<mass.length; i++)
mass[i].index = i;
mass.sort(function(a, b) {
return compareElements(a, b) || a.index - b.index;
});
function compareElements(a, b) {
// something
return a.count - b.count;
}
Problem
I have a problem sorting objects of structure {"name", "count"}: ``` 1. name => "aaa", count => 1 2. name => "bbb", count => 2 3. name => "ccc", count => 3 4. name => "ddd", count => 1 5. name => "eee", count => 1 ``` I need to sort this on "count" (small to big, then big to small). My sort function: ``` mass.sort(compareElements); function compareElements(a, b) { if(a < b) return -1; else if(a > b) return 1; else return 0; } ``` On first call (small to big) I get one result 'res1' on second call (big to small) I get result 'res2' on third call (small to big again) I get 'res3' !== 'res1' !! The order of the elements in res1 and res3 is not the same. I need them to be the same.