Array.sort() Is Producing Unexpected Results When Elements Are Equal?
Solution 1:
The property of a sorting algorithm that leaves elements that compare as equal in their original list order is called stability. The JavaScript spec specifically allows for implementations to use unstable sort algorithms.
The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order).
Now, how you fix your problem depends on your situation. If you know that you "like" the original order, but there's no intrinsic attributes of the objects that would give you that ordering via another sort, then a simple approach would be to make a pass through the array and add another attribute containing the original array index. You could then use that index as a secondary sort key. A final pass after the sort could remove the key (if desired).
Solution 2:
Based on your problem statement, you need to modify arrayToSort
to take into account both strength
and name
arrayToSort.sort(function(a, b) {
if (b.strength == a.strength) {
return a.name.localeCompare(b.name);
} else {
return b.strength - a.strength;
}
});
Post a Comment for "Array.sort() Is Producing Unexpected Results When Elements Are Equal?"