An example of the incorrect use of JavaScript Sort

  • 2020-05-17 04:45:45
  • OfStack

Not long ago, there was a magic problem in my colleague's code. The general process is to sort an array composed of objects, in which 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 will be ranked at the beginning. This is a very simple problem, but the problem is that he USES sort twice to sort this time, first by the properties of a, and then by the values of b. The problem is in the second order.

We take it for granted that in the first sorting, the array is already sorted by the a attribute from large to small. In the second sorting, we simply leave the order of the original array untouched (1 is usually written as 0 or -1 in the method), and only consider bringing the element that b is equal to 1 out of the way. The built-in sort method, javascript (and 1 other languages), USES a collection of several sorting algorithms, and sometimes does not guarantee that the same element remains at 1.

Here is an example from stackoverflow


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 last element would still go from a to t, but we actually run it out of order, because sort's algorithm doesn't keep the order of the original array, which is unstable.

So we should try to avoid this situation. In my colleague's example, combining the logic of sort twice in one time should be feasible. If the logic of sort must be divided into multiple times, then record the order of the original array on the attributes of the element.


Related articles: