js sort function sorting time sorting

1. Function

sort()method for sorting the elements of an array

2. return value

A reference to the array. The array is sorted on the original array , no copy is made.

3. Description

  • If the method is called without parameters, the elements in the array will be sorted alphabetically , that is, in the order of character encoding . To do 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 , which compares two values ​​and returns a number describing 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 array, then return a value less than 0;
    if a is equal to b, return 0;
    if a is greater than b, returns a value greater than 0.

4. Examples

method one:

// a在前为降序,b在前为升序
var list = [
	{
    
    name:"小妹", datetime: "2021-07-09"},
	{
    
    name:"小妹", datetime: "2021-03-09"},
	{
    
    name:"小妹", datetime: "2021-09-09"}
]
list.sort(function(a, b) {
    
    
    return new Date(a.datetime).getTime() - new Date(b.datetime).getTime()
});
console.log(list)

Method 2:

// < 为降序; > 为升序
list.sort(function(a,b){
    
    
  return a.datetime < b.datetime ? 1 : -1
})
console.log(list);

Guess you like

Origin blog.csdn.net/weixin_35773751/article/details/129303278