Array (array) object-> sort () method

1. Definition and usage

  The sort () method is used to sort the elements of the array.

  The default sort order is ascending alphabetical order.

  grammar:

    array.sort(sortfunction)

    parameter:

      sortfunction: Specifies the sort order. Must be a function.

  Note: When the numbers are arranged in alphabetical order, "40" will be arranged before "5".

    To use numeric sorting, you must call it with a function as a parameter.

    The function specifies whether the numbers are sorted in ascending or descending order.

  Example 1: Arrange from 1 to 5

var arr = [1,3,2,5,4];
console.log(arr.sort());
console.log(arr);

  Output:

   Example 2: Arrange from 5 to 1

var arr = [1,3,2,5,4];
console.log(arr.sort().reverse());
console.log(arr);

  Output:

   Example 3: Sort by element length

var arr = ['love','sky'.'student']
arr.sort(function(x,y){
    return x.length - y.length
})
console.log(arr)

  Output:

Guess you like

Origin www.cnblogs.com/abner-pan/p/12694161.html