Get the App
SLTechnology News&Howtos  ›  Development  › 

How javascript uses the sort method in an array

Shulou Source: shulou.com Published: 2022-06-02 17:01:33 09月15日 Update

This article mainly shows you "javascript how to use the sort method in the array", the content is easy to understand, clear, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "javascript how to use the sort method in the array" this article.

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

This article operating environment: windows7 system, javascript1.8.5 version, Dell G3 computer.

JavaScript Array sort () method

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

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

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

This applies to 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 changes the original array.

Grammar

Array.sort (compareFunction)

The parameter compareFunction is optional. A function that defines an alternative sort order.

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

Function (a, b) {return Amurb}

When the sort () method compares two values, it sends the values to the comparison function and sorts the values according to the returned (negative, zero, positive) values.

For example:

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

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

The sort function sorts 40 to a value less than 100.

Return value:

Array object, where 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 murb}). This is all the content of the article "how javascript uses sort methods in arrays". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Sort method array function parameter number content ascending order character string article item order letter syntax negative value learning help primitive two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Xiaomi macOS Shulou Technology MariaDB