Generic way of sorting JSON array by attribute

后端 未结 3 1304
野的像风
野的像风 2020-12-07 21:32

I found out how to sort a JSON array at http://www.devcurry.com/2010/05/sorting-json-array.html

Now I want to sort it in a generic way; so that my sorting function k

3条回答
  •  一生所求
    2020-12-07 21:52

    Something like a:

    function predicateBy(prop){
       return function(a,b){
          if (a[prop] > b[prop]){
              return 1;
          } else if(a[prop] < b[prop]){
              return -1;
          }
          return 0;
       }
    }
    
    //Usage
    yourArray.sort( predicateBy("age") );
    yourArray.sort( predicateBy("name") );
    

提交回复
热议问题