2

If I have an array with objects like this:

percentages_oparea
0: 
    name: test1
    pvalue: 15
1: 
    name: test2    
    pvalue: 16

I can sort this in javascript this way:

percentages_oparea.sort(function(a, b) {
    return parseFloat(b.pvalue) - parseFloat(a.pvalue);
});

and it works correctly:

percentages_oparea
0: 
    name: test2
    pvalue: 16
1: 
    name: test1    
    pvalue: 15

If b.value is exactly the same value a.value I don't want to any sorting. how to achieve this?

I don't know why, but I get this result (test1 and test2 switched indexes) when having exactly the same value in pvalue:

0: 
    name: test2
    pvalue: 15
1: 
    name: test1    
    pvalue: 15

But I want (nothing should change)

0: 
    name: test1
    pvalue: 15
1: 
    name: test2    
    pvalue: 15
bestprogrammerintheworld
  • 5,417
  • 7
  • 43
  • 72
  • 2
    [Sort in javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) is not a [stable](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability) sorting algorithm. So it may swap elements of the same value – Liam Feb 17 '16 at 11:54
  • 1
    Also [Fast stable sorting algorithm implementation in javascript](http://stackoverflow.com/questions/1427608/fast-stable-sorting-algorithm-implementation-in-javascript) – Liam Feb 17 '16 at 12:02

1 Answers1

1

What you're referring is called stability and refers to a sort algorithms capacity to maintain ordering among items that are considered equal. Not all algorithms can make that guarantee, and unfortunately the algorithm that you're using clearly doesn't.

I recommend you take a look at this article regarding sorting algorithms for a complete list.

Neil
  • 5,762
  • 24
  • 36
  • 2
    You can update "apparently doesn't" to "definitely doesn't" by reference to http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11 – Chris Lear Feb 17 '16 at 11:57
  • @ChrisLear It wasn't clear whether or not OP was using the standard sort algorithm so I had to leave room for doubt. ;) – Neil Feb 17 '16 at 13:09