当前位置:网站首页>[JS sort according to the attributes in the object array]

[JS sort according to the attributes in the object array]

2022-07-05 09:28:00 Guodong pudding

【js Sort according to the attributes in the object array 】

var arr = [
    {name:'a',age:9},
    {name:'b',age:12},
    {name:'c',age:8}
];
  
 arr.sort((a,b)=>{
	return a.age -  b.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')))
 *  Examples of use :newArray.sort(sortBy('number',false)) // Express basis number Attribute descending ; If the second parameter is not passed , Default means ascending sort 
     * @param attr  The properties of sorting   Such as number attribute 
     * @param rev true Indicates ascending order ,false null 
     * */
    sortBy: function(attr,rev){
        // The second parameter is not passed   Default ascending order 
        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;
        }
    }
原网站

版权声明
本文为[Guodong pudding]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050927020593.html