This is the 11th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

In the last article, we looked at the array traversal method forEach(), but it was a bit of a problem. There is also the map() method. Others have learned more about JavaScript

In this article, we will continue to learn about sorting methods in JavaScript: sort() is often used in real work.

JavaScript sort()

We’re probably dealing with data every day in a project, and sorting data is one of the algorithms that we use in our programs.

Sorting algorithm

The core of sorting algorithm is to compare the size of two elements, and then return the processed data according to the relevant rules until the processing is finished.

You can compare values directly, but what about strings or two objects? So the process of comparison is abstracted out by a function.

JavaScript’s sort() method is used to sort by passing a method that compares two adjacent elements and positions them according to the method passed.

Each comparison in the sorting process: For the two elements x and y, if x < y, return -1, if x == y, return 0, if x > y, return 1. In this way, the sorting algorithm does not care about the specific comparison process, but directly sorts according to the comparison results.

Sort () Pits that need attention

What happens if you don’t pass comparison arguments to sort()?

// Normal result:
['Banana'.'Apple'.'Orange'].sort();
// ['Apple', 'Banana', 'Orange'];

// Apple ranks last:
['Banana'.'apple'.'Orange'].sort();
// ['Banana', 'Orange", 'apple']

// Number sort pit:
[10.20.1.2].sort();
// [1, 10, 2, 20]
Copy the code

We can sort it more precisely by passing an element handler to sort()

let arr = [10.20.1.2]

arr.sort(function(a, b) {
  return a - b
} )

console.log(arr) // [1, 2, 10, 20]

Copy the code

The method function passed here returns a-b, in ascending order, if return b-a; Is in descending order.

Read more

  • 】 【 Array. The prototype. The map (),
  • JS- special symbol – bit operator
  • 【ES6 – for/of】,
  • JS- Logical operator – short circuit? ,
  • [JavaScript- arrow function],
  • 】 【 JavaScript – forEach (),