Home  >  Article  >  Web Front-end  >  How to use javascript array sort method

How to use javascript array sort method

藏色散人
藏色散人Original
2021-11-03 14:25:445212browse

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)

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}

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});

[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!

Statement:
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