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

Sorting of arrays

There are many kinds of arrays to sort. Today, I learned one of them, the sort method. However, this method has a lot of holes in it, I don’t know if you noticed

sort

Sorting methods change the array!

Sort sort sort sort sort sort sort sort sort sort sort sort sort

The sort method cannot sort frozen arrays, and sorting shared arrays is also problematic

  • Freeze array: object.freeze (my_array), freeze the Object itself.

  • After being frozen, it cannot be modified, added, or deleted

  • There is a problem with sorting the frozen array

  let my_array = ['xn213'.'rainbows'.'beauty'.'moments']
  Object.freeze(my_array)
  my_array.sort()
Copy the code

The code above runs in the Chrome Console panel as follows:

  let my_array = ['xn213'.'rainbows'.'beauty'.'moments']
  my_array.sort()
  // my_array ---> ['beauty', 'moments', 'rainbows', 'xn213']
Copy the code

The array is sorted by the first letter of the string, so let’s look at the following code:

  let my_array = [213.21.2.13.10.3.9.5.29.19]
  my_array.sort()
  // [10, 13, 19, 2, 21, 213, 29, 3, 5, 9]
Copy the code

Here, 2 comes after 19, which is not the sort of size we want. Because the default comparison function of sort converts all comparison objects to strings first, this feature not only slows down performance, but feels like a bug.

No arguments are passed, but we can pass in a custom comparison function.

This function takes two arguments: when comparing sizes, the custom comparison function returns a negative number if it thinks the first argument should come first; Similarly, if the second argument should come first, return a positive number. If the custom comparison function returns 0, the comparison function cannot determine the size of the two.

  function compare(first, second) {
    return first - second
  }
Copy the code

If the array has non-infinite values (Infinity or NaN), the above function doesn’t work and needs to be improved, use your ingenuity. Comments :…