Home > Common Problem > JS array sorting: how to use the sort() method

JS array sorting: how to use the sort() method

小老鼠
Release: 2023-12-27 15:40:46
Original
889 people have browsed it

JavaScript’s Array.prototype.sort() method is used to sort the elements of an array. This method sorts in place, that is, it modifies the original array rather than returning a new sorted array. By default, the sort() method sorts strings according to their Unicode code point values. This means that it is used primarily for sorting strings and numbers, rather than for sorting objects or other complex data types.

JS array sorting: how to use the sort() method

JavaScript’s Array.prototype.sort() method is used to sort the elements of an array. This method sorts in place, that is, it modifies the original array rather than returning a new sorted array.

By default, the sort() method sorts strings according to their Unicode code point values. This means that it is used primarily for sorting strings and numbers, rather than for sorting objects or other complex data types.

Here is a simple example:

javascript

let arr = [5, 2, 3, 1, 4];  
arr.sort();  
console.log(arr); // 输出: [1, 2, 3, 4, 5]
Copy after login

If you want to sort by the size of the numbers, you need to provide a comparison function:

javascript

let arr = [5, 2, 3, 1, 4];  
arr.sort(function(a, b) {  
  return a - b;  
});  
console.log(arr); // 输出: [1, 2, 3, 4, 5]
Copy after login

This comparison function determines the sorting order. If the function returns a value less than 0, then a will be sorted before b; if it returns a value greater than 0, then a will be sorted after b; if it returns 0, then the positions of a and b will remain unchanged.

If you want to sort in descending order, you can write like this:

javascript

let arr = [5, 2, 3, 1, 4];  
arr.sort(function(a, b) {  
  return b - a;  
});  
console.log(arr); // 输出: [5, 4, 3, 2, 1]
Copy after login

In addition, the sort() method can also accept an optional parameter to specify Base value for sorting. For example, if you want to sort by the first element in the array, you can do this:

javascript

let arr = [3, 1, 2];  
arr.sort(function(a, b) {  
  return a[0] - b[0];  
});  
console.log(arr); // 输出: [1, 2, 3]
Copy after login

The above is the detailed content of JS array sorting: how to use the sort() method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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