JavaScript array sort

The Sort() method is one of the most powerful array methods

Sort an array
  • The sort() method sorts arrays alphabetically

Inversion array
  • The reverse() method reverses the elements in an array, sorting the array in descending order

By default, the sort() function sorts the values in string order

This function works well with strings (” Apple “comes before” Banana “)

However, if the numbers are sorted by string, “25” is greater than “100” because “2” is greater than “1”

As a result, the sort() method produces incorrect results when sorting values.

The ratio function is used to fix this problem:

Descending an array using the same technique:

The ratio of function

The purpose of the comparison function is to define an alternative sort order

The comparison function should return a negative, zero, or positive value, depending on the argument:

Function(a, b) { return a – b}

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

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

This function evaluates 40-100 and returns -60(negative)

The sorting function will sort 40 to a value lower than 100

Random sequence

Find the highest (or lowest) array value

JavaScript does not provide built-in functions to find the largest or smallest array value in an array

However, after sorting, you can use the index to get the highest or lowest value

Ascending order

Descending order

But sorting an array is inefficient if you just look for the maximum value. You can use the following methods

Use math.max () for arrays

  • You can use math.max. apply to find the highest value in the array

  • Similarly, the minimum is math.min ()

Sort object array

The sort() method can sort even if objects have attributes of different data types

The solution is to compare attribute values by comparing functions: