js sort Ordenar según el valor del atributo de un objeto en la matriz

El método de clasificación recibe una función como parámetro, y se usa una función anidada para recibir el nombre de la propiedad del objeto, y otras partes usan la clasificación.
var arr = [ 
    {name: 'zoop', age : 3},
    {name: 'gpp', age:18},
    {name: 'yjj', age: 20}
];

function compare(property){
    return function(a,b){
        var val1 = a[property];
        var val2 = b[property];
        return val1 - val2
    }
}

console.log(arr.sort(compare('age')))

inserte la descripción de la imagen aquí

Ordenar por diferentes parámetros
/**数组根据数组对象中的某个属性值进行排序的方法 
     * 使用例子:newArray.sort(sortBy('number',false)) //表示根据number属性降序排列;若第二个参数不传递,默认表示升序排序
     * @param attr 排序的属性 如number属性
     * @param rev true表示升序排列,false降序排序
     * */
    sortBy: function(attr,rev){
        //第二个参数没有传递 默认升序排列
        if(rev ==  undefined){
            rev = 1;
        }else{
            rev = (rev) ? 1 : -1;
        }
        
        return function(a,b){
            a = a[attr];
            b = b[attr];
            if(a < b){
                return rev * -1;
            }
            if(a > b){
                return rev * 1;
            }
            return 0;
        }
    }

Supongo que te gusta

Origin blog.csdn.net/qq_42697806/article/details/124002106
Recomendado
Clasificación