JavaScript array sort sort () method

var fruits = [ "Banana", "Orange", "the Apple", "Mango" ]; 
fruits.sort ();             // for sorting elements in fruits

By default, Sort () function is a character string Unicodecode.

This function is suitable for strings ( "Apple" will be sorted before "Banana").

However, if the numbers to sort character strings, then "25" is greater than "100", since "2" is greater than "1."

For this reason, the Sort () method can produce incorrect results when sorted values.

 

Comparing the ratio value by the function

Objective To compare another function is to define the sort order.

The comparison function should return a negative, zero or positive, depending on the parameters

Ascending

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});

Sort Descending

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});

Random order sort

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()}); 

Complex array, the array elements according to a property in the sort

var sourceList = [{ 
        bscore: 222 , 
        name: 'ha' 
    }, 
    { 
        bscore: 34 is , 
        name: 'ha' 
    }, 
    { 
        bscore: 465 , 
        name: 'ha' 
    }, 
    { 
        bscore: 67 , 
        name: 'ha' 
    }, 
    { 
        bscore: 243 , 
        name: 'ha' 
    }, 
    { 
        bscore: 135 , 
        name:'哈哈'
    }
]
sourceList.sort((a, b) => {
    return a.bscore - b.bscore
})

 

Guess you like

Origin www.cnblogs.com/---godzilla---/p/11528571.html