4

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.

Jan Doggen
  • 8,799
  • 13
  • 70
  • 144
Dima Dima
  • 43
  • 1
  • 4

2 Answers2

4

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;
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

If your objects are like:

var arrObj = {
   name: "aaa",
   count: 1
};

Use this function for comparing:

function compareElements(a, b)
{
  return a.count - b.count;
}
Artyom Neustroev
  • 8,627
  • 5
  • 33
  • 57