Object arrays are sorted by the properties of an object

The most common way to sort an array is to sort by the first letter or number size of the elements in the array using the sort() method

var arr = [2,5,13,7,4,9,1];
var arr1 = arr.sort();
console.log(arr);  // [1, 13, 2, 4, 5, 7, 9]
console.log(arr1);   // [1, 13, 2, 4, 5, 7, 9]

The sort() method changes the original array, and the sort method is not strictly ordered by the number size.
If you want to sort the array by size, you need to add a comparison function in the sort() method

var arr = [2,5,13,7,4,9,1];
arr.sort(function(a,b){
    return a-b;    // -1 ascending 
})
console.log(arr);   // [1, 2, 4, 5, 7, 9, 13]

compare function return value characteristics:
If a is less than b, a should appear before b in the sorted array (i.e. ascending), then a value less than 0 will be returned
0 if a equals b
If a is greater than b, a value greater than 0 is returned

Can we use sort method to sort the array of objects according to their properties?

The answer is yes
Just as the above array is sorted by size and the comparison function is specified, only the attributes of the object are compared at this time
Upper Code: for the following object array, sort by age

var infoObj=[
            {
                name:"Zhang San",
                sex:'female',
                age:30
            },
            {
                name:"Li Si",
                sex:'male',
                age:20
            },
            {
                name:"Wang Wu",
                sex:'female',
                age:40
            }
        ];
        // Specify the comparison function for sorting
    function compare(property){
         return function(obj1,obj2){
             var value1 = obj1[property];
             var value2 = obj2[property];
             return value1 - value2;     // Ascending order
         }
    }
    var sortObj = infoObj.sort(compare("age"));
    console.log(sortObj); // 

The final printed results are as follows:

[
    {
        name:"Li Si",
        sex:'male',
        age:20
    },
    {
        name:"Zhang San",
        sex:'female',
        age:30
    },
    {
        name:"Wang Wu",
        sex:'female',
        age:40
    }
];

This completes the object array sorting according to the object properties! !!

Tags: less

Posted on Tue, 05 May 2020 16:57:34 -0400 by tommy445