Wednesday, 25 August 2021

Javascript Sort an array

 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:

  1. If compare(a,b) is less than zero, the sort() method sorts a to a lower index than b. In other words, a will come first.
  2. If compare(a,b) is greater than zero, the sort() method sort b to a lower index than a, i.e., b will come first.
  3. If compare(a,b) returns zero, the sort() method considers a equals b and leaves their positions unchanged.

No comments:

Post a Comment