Suppose I have this array:
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)" }
];
And this function to sort the array by name:
array.sort(function(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
And ECMAScript language specifications that tell me that:
The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order).
So, after sorting, the two items with name = background color could appear in any order i.e.:
[
{ 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)" },
...
]
How can I sort the array so that items with same name maintain their relative order? I would rather not hardcode anything.