The objects in the js array are sorted by attributes, if the attribute values are the same, then other attributes are used for sorting

Requirement: The data is sorted according to the id attribute from small to large, and if the id is the same, then it is sorted according to the sid from small to large to achieve:

var data = [
{"id": 1, "sid": 3}, 
{"id": 2, "sid": 2}, 
{"id": 3, "sid": 4}, 
{"id": 1, "sid": 1},
{"id": 1, "sid": 2}];

data.sort(function (a, b) {
    if (a.id != b.id) {
        return a.id - b.id;
    }
    return a.sid - b.sid;
});

console.log(data);

 

Guess you like

Origin blog.csdn.net/qq_40015157/article/details/113368797