When trying to sort a list of divs with javascript, the results for duplicate values is inconsistent:
In the case there are duplicate values, the result of the sorting depends on which div was places first in the DOM. How can we sort these duplicates so that independently of the DOM order the result is the same, by sorting on a second variable (data-foo)?
Code:
<script>
var $wrapper = $('.table');
$wrapper.find('.cell').sort(function (b, a) {
return +a.getAttribute('data-number') - +b.getAttribute('data-number');
})
.appendTo( $wrapper);
</script>
<div class="table">
<div class="cell" data-number="15.2" data-foo="324"></div>
<div class="cell" data-number="15.2" data-foo="223"></div>
<div class="cell" data-number="52.8" data-foo="15468"></div>
<div class="cell" data-number="16.0" data-foo="32"></div>
<div class="cell" data-number="15.2" data-foo="454"></div>
<div class="cell" data-number="41.9" data-foo="787"></div>
<div class="cell" data-number="12.3" data-foo="432"></div>
<div class="cell" data-number="12.3" data-foo="23"></div>
</div>
Change the sorting function so it checks whether the first sort fields are equal. If they are, it returns a result based on the second sort field instead.
$wrapper.find('.cell').sort(function (b, a) {
var number1 = +a.getAttribute('data-number'),
number2 = +b.getAttribute('data-number');
if (number1 == number2) {
return +a.getAttribute('data-foo') - +b.getAttribute('data-foo');
} else {
return number1 - number2;
}
})