Home > Web Front-end > JS Tutorial > body text

How to use javascript array sort method

藏色散人
Release: 2021-11-03 14:25:44
Original
5217 people have browsed it

The function of the javascript array sort method is to sort the items of the array. Its usage syntax is "array.sort(compareFunction)", where the parameter compareFunction defines a function that replaces the sort order.

How to use javascript array sort method

The operating environment of this article: windows7 system, javascript version 1.8.5, Dell G3 computer.

How to use the javascript array sort method?

JavaScript Array sort() method

The sort() method sorts the items of an array.

The sort order can be alphabetical or numerical, ascending (upward) or descending (downward).

By default, the sort() method will sort values ​​as strings in alphabetical and ascending order.

This works for strings ("Apple" appears before "Banana"). However, if the numbers are sorted by string, "25" is greater than "100" because "2" is greater than "1".

Because of this, the sort() method produces incorrect results when sorting numbers.

You can solve this problem by providing a "comparison function" (see "Parameter values" below).

Note: The sort() method will change the original array.

Syntax

array.sort(compareFunction)
Copy after login

Parameters compareFunction Optional. Defines a function that overrides the sort order.

The function should return a negative, zero, or positive value, depending on the parameters, for example:

function(a, b){return a-b}
Copy after login

sort() method When comparing two values, the value is sent to the comparison function, Sorts values ​​based on the returned (negative, zero, positive) value.

Example:

When comparing 40 and 100, the sort() method calls the comparison function (40,100).

This function calculates 40-100 and returns -60 (negative value).

The sort function sorts 40 into values ​​less than 100.

Return value:

Array object in which the items are sorted.

JavaScript version: ECMAScript 1

Example

Sort the numbers in the array in ascending order:

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Copy after login

[Recommended learning: javascript basics Tutorial

The above is the detailed content of How to use javascript array 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