Not long ago, a very magical problem came into my colleague's code. The rough process is to sort an array composed of objects, where attribute a is used to sort, and attribute b is a preferred condition. When b equals 1, no matter what the value a is, it is ranked at the beginning. This is a very simple problem. The problem is that he uses sort twice to implement sorting this time, first sorting according to the attribute of a, and then sorting according to the value of b. The problem lies in the second sorting.
We will take it for granted that in the first sorting, the array has been sorted from large to small according to the attributes of a. In the second time, we just need not move the order of the original array (usually written as returning 0 or -1 in the method), and only consider mentioning elements with b equal to 1 to the front. But in fact, this is related to the sort algorithm chosen by the language. The built-in sort method of javascript (and other languages together) uses a collection of several sort algorithms, and sometimes it cannot guarantee that the position of the same elements remains consistent.
Below is an example found from stackoverflow
The code copy is as follows:
var arrayToSort = [
{name: 'a', strength: 1}, {name: 'b', strength: 1}, {name: 'c', strength: 1}, {name: 'd', strength: 1},
{name: 'e', strength: 1}, {name: 'f', strength: 1}, {name: 'g', strength: 1}, {name: 'h', strength: 1},
{name: 'i', strength: 1}, {name: 'j', strength: 1}, {name: 'k', strength: 1}, {name: 'l', strength: 1},
{name: 'm', strength: 1}, {name: 'n', strength: 1}, {name: 'o', strength: 1}, {name: 'p', strength: 1},
{name: 'q', strength: 1}, {name: 'r', strength: 1}, {name: 's', strength: 1}, {name: 't', strength: 1}
];
arrayToSort.sort(function (a, b) {
return b.strength - a.strength;
});
arrayToSort.forEach(function (element) {
console.log(element.name);
});
We would think that the value of the last element is still from a to t, but the actual result is out of order. This is because the sort algorithm does not retain the order of the original array, that is, unstable.
Then we should try to avoid this situation. In the example of my colleague, merging the logic of two sorts in one should be a feasible way. If it must be divided into multiple sorts, then the order of the original array is recorded on the attributes of the elements.