Imagine I am faced with an array like this:
var array = [
{ name: "border-color", value: "#CCCCCC" },
{ name: "color", value: "#FFFFFF" },
{ name: "background-color", value: "rgb(0, 0, 0)" },
{ name: "background-color", value: "rgba(0, 0, 0, .5)" }
];
I have a function set up to sort the elements of the array by their names:
array.sort(function(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
According to the ECMAScript language specifications:
The sorting operation is not guaranteed to be stable, meaning items that compare equally may not maintain their original order.
Therefore, post-sorting, the two entries with the same 'name' could end up in any position, such as:
[
{ name: "background-color", value: "rgb(0, 0, 0)" },
{ name: "background-color", value: "rgba(0, 0, 0, .5)" },
...
]
Or
[
{ name: "background-color", value: "rgba(0, 0, 0, .5)" },
{ name: "background-color", value: "rgb(0, 0, 0)" },
...
]
Is there a way to sort the array so that elements with matching names retain their relative order? I'd prefer not to hardcode anything.