Home > Java > javaTutorial > body text

JS array sorting: in-depth analysis of the working principle and mechanism of the sort() method

WBOY
Release: 2023-12-28 11:47:38
Original
1903 people have browsed it

JS array sorting: in-depth analysis of the working principle and mechanism of the sort() method

In-depth understanding of JS array sorting: the principle and mechanism of the sort() method requires specific code examples

Introduction: Array sorting is in our daily front-end development work One of the very common operations. The array sorting method sort() in JavaScript is one of our most commonly used array sorting methods. However, do you really understand the principles and mechanisms of the sort() method? This article will give you an in-depth understanding of the principles and mechanisms of JS array sorting, and provide specific code examples.

1. Basic usage of sort() method

First, let’s understand the basic usage of sort() method. The sort() method can sort the array in place, which means that it does not create a new array, but directly modifies the original array.

sort()The method will convert the elements of the array into strings by default and sort them in ascending order according to Unicode positions.

For example, we have an array containing numeric types:

let arr = [8, 3, 6, 2, 9, 1];
arr.sort();
console.log(arr); // [1, 2, 3, 6, 8, 9]
Copy after login

As can be seen from the above example, the sort() method will convert the elements in the array into a string and sorted. However, this default string sorting does not apply to numeric array sorting. Next, we will explore how to implement forward and reverse ordering for numeric types.

2. Sorting using comparison functions

sort()The method can accept a comparison function as a parameter, which is used to define sorting rules. The comparison function accepts two parameters, representing the two elements to be compared.

  • If the return value of the comparison function is less than 0, then the first element will be sorted first.
  • If the return value of the comparison function is greater than 0, then the second element will be sorted first.
  • If the return value of the comparison function is equal to 0, then the relative position of the two elements remains unchanged.

Now, let’s take a look at how to use comparison functions to achieve forward and reverse order.

  1. Order in positive order

    let arr = [8, 3, 6, 2, 9, 1];
    arr.sort((a, b) => a - b);
    console.log(arr); // [1, 2, 3, 6, 8, 9]
    Copy after login

In the above code, we use the comparison function(a, b) => a - b to achieve positive order. If the return value of the comparison function a - b is less than 0, it means placing a in front of b to achieve ascending order.

  1. Arrange in reverse order

    let arr = [8, 3, 6, 2, 9, 1];
    arr.sort((a, b) => b - a);
    console.log(arr); // [9, 8, 6, 3, 2, 1]
    Copy after login

In the above code, we use the comparison function(a, b) => b - a to achieve reverse order. If the return value of the comparison function b - a is less than 0, it means placing b in front of a to achieve descending order.

3. Customized sorting rules

In addition to sorting in forward and reverse order, we can also customize the sorting rules according to our own needs.

For example, if we want to arrange a string array according to the string length, we can achieve it like this:

let arr = ['a', 'abcd', 'ab', 'abc'];
arr.sort((a, b) => a.length - b.length);
console.log(arr); // ['a', 'ab', 'abc', 'abcd']
Copy after login

In the above code, we use the comparison function (a, b) => a.length - b.length to sort in ascending order by string length.

4. Sorting of complex objects

If we want to sort an array containing complex objects, we need to specify the basis for sorting in the comparison function.

For example, we have an array containing student data. Each student object has two attributes: name and score. We want to sort students according to their scores, which can be achieved like this:

let students = [
  { name: 'Alice', score: 90 },
  { name: 'Bob', score: 80 },
  { name: 'Charlie', score: 70 }
];

students.sort((a, b) => b.score - a.score);
console.log(students); // [{ name: 'Alice', score: 90 }, { name: 'Bob', score: 80 }, { name: 'Charlie', score: 70 }]
Copy after login

In the above code, we use the comparison function (a, b) => b.score - a.score To sort students in descending order by their scores.

Conclusion

Through this article's in-depth understanding of the principles and mechanisms of the sort() method, we know how to use comparison functions to implement forward order, reverse order, and customization Sorting rules, and learned to sort in complex arrays of objects. I hope the content of this article can help you and improve your understanding and use of JavaScript array sorting.

The above is the detailed content of JS array sorting: in-depth analysis of the working principle and mechanism of the sort() method. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!