https://www.javascripttutorial.net/javascript-array-sort/
array.sort(comparefunction)
Code language: CSS (css)
The sort()
method accepts an optional argument which is a function that compares two elements of the array.
If you omit the compare function, the sort()
method sorts the elements with the sort order based on the Unicode code point values of elements as mentioned earlier.
The compare function of the sort()
method accepts two arguments and returns a value that determines the sort order. The following illustrates the syntax of the compare function:
function compare(a,b) {
// ...
}
Code language: JavaScript (javascript)
The compare()
function accepts two arguments a
and b
. The sort()
method will sort elements based on the return value of the compare()
function with the following rules:
- If
compare(a,b)
is less than zero, thesort()
method sortsa
to a lower index thanb
. In other words,a
will come first. - If
compare(a,b)
is greater than zero, thesort()
method sortb
to a lower index thana
, i.e., b will come first. - If
compare(a,b)
returns zero, thesort()
method considers a equals b and leaves their positions unchanged.
No comments:
Post a Comment