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
2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You can update "apparently doesn't" to "definitely doesn't" by reference to ecma-international.org/ecma-262/5.1/#sec-15.4.4.11
@ChrisLear It wasn't clear whether or not OP was using the standard sort algorithm so I had to leave room for doubt. ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.