A very magical problem occurred in a colleague’s code not long ago. The general process is to sort an array composed of objects. The attribute a is used for sorting, and the attribute b is used as a preferred condition. When b is equal to 1 Whatever the value of a is, it comes first. This is a very simple question, but the problem is that he uses sort twice to implement sorting this time, first sorting according to the attributes of a, and then sorting according to the value of b. The problem lies in the second sort.
We 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 only need to not change the order of the original array (usually written in the method to return 0 or -1), only consider bringing the elements with b equal to 1 to the front. But in fact, this is related to the sorting algorithm selected by the language. The built-in sort method of JavaScript (and other languages) uses a collection of several sorting algorithms, and sometimes it does not guarantee that the positions of the same elements are consistent.
The following is an example found from stackoverflow
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 running result is out of order. This is because the sort algorithm does not retain the order of the original array, which is unstable.
Then we should try our best to avoid this situation from happening. Taking the example of my colleague, it should be a feasible way to merge the logic of two sort into one. If it must be divided into multiple sort, then merge the logic of the original array The order is recorded in the element's attributes.