javascript sort() method


  Translation results:

英[sɔ:t]   美[sɔ:rt]   

n.Classification, category; quality, nature; method; a group

vt.& vi.Classification; rectification, arrangement ; suitable for

vt. to select; to classify; to put in order

vi. to classify; to communicate; to coordinate

Third person singular: sorts Plural: sorts Present participle: sorting past tense: sorted past participle: sorted

javascript sort() methodsyntax

How to use the sort() method?

The sort() method is used to sort the elements of an array and return the array. The sort() method is now stable. The default sort order is based on string Unicode code points.

Function: Used to sort the elements of the array.

Syntax: arrayObject.sort(sortby)

Parameters: sortby Optional. Specifies the sort order. Must be a function.​

Returns: Reference to the array. Please note that the array is sorted on the original array, no copy is made.

Note: If no parameters are used when calling this method, the elements in the array will be sorted in alphabetical order. To be more precise, they will be sorted in the order of character encoding. To achieve this, the elements of the array should first be converted to strings (if necessary) for comparison. If you want to sort by other criteria, you need to provide a comparison function that compares two values ​​and returns a number that describes the relative order of the two values. The comparison function should have two parameters a and b, and its return value is as follows: if a is less than b, a should appear before b in the sorted array, then a value less than 0 is returned. If a equals b, returns 0. If a is greater than b, returns a value greater than 0.

javascript sort() methodexample

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<script type="text/javascript">

    var arr = new Array(6)
    arr[0] = "George"
    arr[1] = "John"
    arr[2] = "Thomas"
    arr[3] = "James"
    arr[4] = "Adrew"
    arr[5] = "Martin"

    document.write(arr + "<br />")
    document.write(arr.sort())

</script>

</body>
</html>

Run instance »

Click the "Run instance" button to view the online instance

Popular Recommendations

Home

Videos

Q&A