天天看點

兩種根據數組中對象的某一個屬性值對數組進行重新排序的方法

<== js sort方法根據數組中對象的某一個屬性值進行排序

var arr = [
    {name:'張三',age:},
    {name:'李四',age:},
    {name:'王五',age:},
     {name:'錢六',age:},
];

function compare(property){
    return function(a,b){
        var value1 = a[property];
        var value2 = b[property];
        return value1 - value2;
    }
}
console.log(arr.sort(compare('age')))
           
兩種根據數組中對象的某一個屬性值對數組進行重新排序的方法

<== 直接對比數組中的屬性值

var arr = [ {name:'張三',age:10}, {name:'李四',age:16}, {name:'王五',age:8}, {name:'錢六',age:22}, ]; console.log(arr.sort(function(arr1, arr2){ return arr1.age>arr2.age;}));

兩種根據數組中對象的某一個屬性值對數組進行重新排序的方法

繼續閱讀