Javascript array sorting details

  • 2020-03-30 04:11:23
  • OfStack

If you've been working with javascript for a while, you know the array sort function sort is a method in the array prototype, array. Prototype.sort (),sort(compareFunction).
If compareFunction is not supplied, elements are sorted by throwing them to strings and comparing strings in lexicographic (" dictionary "or" telephone book, "not numerical) order. For example, "80" comes before "9" in lexicographic order, but in a numeric sort 9 comes before 80.

Here are some simple examples:


// Output [1, 2, 3]
console.log([3, 2, 1].sort()); // Output ["a", "b", "c"]
console.log(["c", "b", "a"].sort()); // Output [1, 2, "a", "b"]
console.log(["b", 2, "a", 1].sort());

As you can see from the above example, the default is to sort by the order of the letters in the dictionary.

Fortunately, sort accepts a custom comparison function, as shown in the following example:


function compareFunction(a, b) {
 if( a > b) {
  return -1;
 }else if(a < b) {
  return 1;
 }else {
  return 0;
 }
}
//Outputs ["zuojj", "Benjamin", "1"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction));

After sorting we have another question, how do we control ascending and descending orders?


function compareFunction(flag) {
 flag = flag ? flag : "asc";
 return function(a, b) {
  if( a > b) {
   return flag === "desc" ? -1 : 1;
  }else if(a < b) {
   return flag === "desc" ? 1 : -1;
  }else {
   return 0;
  }
 };
}
//Outputs ["1", "Benjamin", "zuojj"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction()));
//Outputs ["zuojj", "Benjamin", "1"]
console.log(["Benjamin", "1", "zuojj"].sort(compareFunction("desc")));

The comparFunction collation looks like this:
If it returns a negative number, a will be sorted to a lower index in the array.
If it returns a positive number, a will be sorted to a higher index.
And if it returns 0 no sorting is necessary.

Here's a quote from Mozilla MDN:
The behavior of The sort method changed between JavaScript 1.1 and JavaScript 1.2. To explain this description, let's look at an example:

In JavaScript 1.1, on some platforms, the sort method does not work. This method works on all platforms for JavaScript 1.2.

In JavaScript 1.2, this method no longer converts undefined elements to null; Instead it sorts them to the high end of the array.


var arr = [];
arr[0] = "Ant";
arr[5] = "Zebra";
//Outputs ["Ant", 5: "Zebra"]
console.log(arr);
//Outputs 6
console.log(arr.length);
//Outputs "Ant*****Zebra"
console.log(arr.join("*"));
//Sorting < br / > var sortArr = arr.sort();
//Outputs ["Ant", "Zebra"]
console.log(sortArr);
//Outputs 6
console.log(sortArr.length);
//Outputs "Ant*Zebra****"
console.log(sortArr.join("*"));

Refer to the link: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/sort


Related articles: