Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

As a front-end developer, we all know that there is a sort method for arrays: sort, which is handy for ascending arrays such as arr.sort((a,b) => a-b), but what is behind sort? Why is a minus B in ascending order?

Let’s look at sort from all sides:

Introduction:

The sort() method sorts the elements of an array using an in-place algorithm and returns the array. The default sort order is built when converting elements to strings and then comparing their UTF-16 code unit value sequences

Because it is implementation-dependent, the temporal and spatial complexity of sorting cannot be guaranteed.

const months = ['March'.'Jan'.'Feb'.'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1.30.4.21.100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]
Copy the code

Grammar:

arr.sort([compareFunction])
Copy the code

Parameters:

CompareFunction (optional)

A function that specifies an order in which, if omitted, elements are sorted by the Unicode point of each character in the converted string.

FirstEle: The first element used for comparison

SecondEle: The second element used for comparison

return

Sorted array. Note that the array is sorted in place and is not copied.

Description:

If compareFunction is not specified, the element is sorted by the Unicode loci of the characters in the converted string. For example, “Banana” will be placed before “cherry”. When numbers are sorted from smallest to largest, 9 appears before 80, but because (no compareFunction is specified) the comparison number is converted to a string first, “80” precedes “9” in Unicode order.

If compareFunction is specified, the array is sorted by the value returned from calling the function. That is, a and B are the two elements to be compared:

  • ifcompareFunction(a, b)Less than 0, a will be placed before B;
  • ifcompareFunction(a, b)Is equal to 0, the relative positions of a and b remain the same. Note: The ECMAScript standard does not guarantee this behavior, and not all browsers comply (Mozilla prior to 2003, for example);
  • ifcompareFunction(a, b)Greater than 0, b will be placed before A.
  • compareFunction(a, b)The same comparison must always be returned for the same input, or the sorting result will be indeterminate.

So, the comparison function has the following format

function compare(a, b) {
  if (a < b ) {           // By some sort of comparison, a is less than B
    return -1;
  }
  if (a > b ) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
Copy the code

To compare numbers instead of strings, the comparison function can simply be a minus b, and the following function will sort the array in ascending order

function compareNumbers(a, b) {
  return a - b;
}
Copy the code

The sort method can be conveniently written using function expressions:

var numbers = [4.2.5.1.3];
numbers.sort(function(a, b) {
  return a - b;
});
console.log(numbers); It can also be written as:var numbers = [4.2.5.1.3];
numbers.sort((a, b) = > a - b);
console.log(numbers);

// [1, 2, 3, 4, 5]
Copy the code

Objects can be sorted by a property;

var items = [
  { name: 'Edward'.value: 21 },
  { name: 'Sharpe'.value: 37 },
  { name: 'And'.value: 45 },
  { name: 'The'.value: -12 },
  { name: 'Magnetic' },
  { name: 'Zeros'.value: 37}];// sort by value
items.sort(function (a, b) {
  return (a.value - b.value)
});

// sort by name
items.sort(function(a, b) {
  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
  if (nameA < nameB) {
    return -1;
  }
  if (nameA > nameB) {
    return 1;
  }

  // names must be equal
  return 0;
});
Copy the code

Example:

var stringArray = ["Blue"."Humpback"."Beluga"];
var numericStringArray = ["80"."9"."700"];
var numberArray = [40.1.5.200];
var mixedNumericArray = ["80"."9"."700".40.1.5.200];

function compareNumbers(a, b)
{
  return a - b;
}

console.log('stringArray:' + stringArray.join());
console.log('Sorted:' + stringArray.sort());

console.log('numberArray:' + numberArray.join());
console.log('Sorted without a compare function:'+ numberArray.sort());
console.log('Sorted with compareNumbers:'+ numberArray.sort(compareNumbers));

console.log('numericStringArray:'+ numericStringArray.join());
console.log('Sorted without a compare function:'+ numericStringArray.sort());
console.log('Sorted with compareNumbers:'+ numericStringArray.sort(compareNumbers));

console.log('mixedNumericArray:'+ mixedNumericArray.join());
console.log('Sorted without a compare function:'+ mixedNumericArray.sort());
console.log('Sorted with compareNumbers:'+ mixedNumericArray.sort(compareNumbers));
Copy the code

The return result for this example is as follows. The output shows that when the comparison function is used, the numeric array is sorted by numeric size.

stringArray: Blue,Humpback,Beluga
Sorted: Beluga,Blue,Humpback

numberArray: 40.1.5.200
Sorted without a compare function: 1200,40,5Sorted with compareNumbers: 1,5,40,200

numericStringArray: 80,9,700
Sorted without a compare function: 700,80,9
Sorted with compareNumbers: 9,80,700

mixedNumericArray: 80,9,700,40,1,5,200
Sorted without a compare function: 1200,40,5,700,80,9Sorted with compareNumbers: 1,5,9,40,80,200,700
Copy the code