JavaScript sorting sort() method (to solve the sorting (confusion) problem between null, undefined, and 0)

The return value of the sort function is a reference to the original sorted array. Note that the array is sorted in-place, no copying is done.

insert image description here
insert image description here

question:

If an object in the array is a null value, what happens to the sorting? (Obviously not sorted by age because there are null and undefined)

var arr=[{
    
    "age":24,name:'zs'},{
    
    "age":0,name:'ls'},{
    
    "age":0,name:'gr'}{
    
    "age":null,name:'yo'},{
    
    "age":7,name:'pl'},{
    
    "age":undefined,name:'tt'}{
    
    "age":null,name:'jz'},{
    
    "age":0,name:'mn'},{
    
    "age":undefined,name:'we'}]

//[{"age": 0,"name": "ls"},{"age": 0,"name": "gr"},{"age": null,"name": "yo"},
//{"age": null,"name": "jz"},{"age": 0,"name": "mn"},{"age": 7,"name": "pl"},
//{"age": 24,"name": "zs"},{"age":undefined,"name": "tt"},
//{"age":undefined,"name": "we"}]
console.log(arr.sort(compare("age")));

Simple arrays and object arrays behave differently, as follows:
insert image description here

Solution:

In the sorting method provided by the sort method, if the returned number is 0, the original order will be maintained. If the returned number > 0, then a will be placed after b. If the returned number < 0, then a will be placed before b.

If the field may be undefined, then we need special judgment to deal with it.

First judge if the sorting fields of a and b are undefined, return 0 to keep the original order.

Then judge if the field of a is undefined but the sorting field of b exists, return >0 and put a after b.

Then judge that if the sorting field of b is undefined but the sorting field of a exists, then return <0 and place a before b.

Finally, when both the sorting fields of a and b exist, the order of the returned results calculated using the sorting fields of a and b is used to determine the order

const compare = function (orderType, props) {
    
    
    return function (obj1, obj2) {
    
    
        var val1 = obj1[props];
        var val2 = obj2[props];
        if (val1 == null && val2 == null) {
    
    
            return 0;
        }
        if(val1 == null){
    
    
            return 999;
	    }
	    if(val2 == null){
    
    
	        return -999
	    }
        if (typeof val1 === 'string' && typeof val2 === 'string') {
    
    
            if (val1 < val2) {
    
    
                return -1;
            } else if (val1 > val2) {
    
    
                return 1;
            }
            return 0;
        }
	    return orderType === 'ascend' ? val1 - val2 : val2 - val1;
    } 
}
const orderType = 'descend'; // descend
const rr = prodInfo.sort(compare(orderType, 'num'))
console.log(rr.map(item => item.num))

Reference link 1: https://www.cnblogs.com/gby-web/p/16743564.html
Reference link 2: https://juejin.cn/post/7165121725678665765/


Double sort (secondary sort):

Secondary sorting refers to sorting the data twice, the first time by an attribute, and the second time by another attribute. This sorting method can be used in a variety of scenarios, such as sorting students by grade and age, sorting products by price and sales, and so on. When implementing secondary sorting, various algorithms can be used, such as bubble sorting, quick sorting, merge sorting, and so on. The most suitable algorithm needs to be selected according to the specific scenario and data volume.


Sort in specified order

// ## 按指定序列排序
const arr = [
    {
    
     name: 'A', type: 'fly' },
    {
    
     name: 'B', type: 'blur' },
    {
    
     name: 'C', type: 'wipe' },
    {
    
     name: 'D', type: 'cube' },
    {
    
     name: 'B', type: 'zoom' },
    {
    
     name: 'C', type: 'cube' },
    {
    
     name: 'E', type: 'iris' },
    {
    
     name: 'F', type: 'fade' },
    {
    
     name: 'F', type: '' }
];
// 按type的指定顺序排序
const order = ['wipe', 'fly', 'iris', 'flip', 'cube', 'blur', 'fade', 'zoom'];
arr.sort((star, next) => {
    
    
    return order.indexOf(star.type) - order.indexOf(next.type);
});

console.log(arr);

random order

// ## 随机排序
arr.sort((a, b) => {
    
    
    return Math.random() - 0.5
}) 
console.log(arr);

Guess you like

Origin blog.csdn.net/yexudengzhidao/article/details/131328091