js objects sorted according to the attributes 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')))
* Use Examples: newArray.sort (the sortBy ( 'number', to false )) // represents a descending order according to the attribute number; if the second parameter is not transmitted, default representation ascending sort 
     * @param sort attributes attr number attribute
      * @ param rev true indicates ascending, false descending order
      * * / 
    the sortBy: function (attr, Rev) {
         // second default parameter is not passed ascending 
        IF (Rev ==   undefined) { 
            Rev =. 1 ; 
        } the 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;
        }
    }

 

  

Guess you like

Origin www.cnblogs.com/huanhuan55/p/11511119.html