How to sort a JavaScript array of objects by nested object property?

后端 未结 8 1826
广开言路
广开言路 2020-12-01 06:37

I have this function to sort a JavaScript array of objects based on a property:

// arr is the array of objects, prop is the property to sort by
var sort = fu         


        
相关标签:
8条回答
  • 2020-12-01 07:00

    Try this (used a recursive function to get nested value, you can pass the nested property as nestedobj.property): You can use this for any level of hierarchy

    // arr is the array of objects, prop is the property to sort by
    var getProperty = function(obj, propNested){
     if(!obj || !propNested){
      return null;
     }
     else if(propNested.length == 1) {
        var key = propNested[0];
        return obj[key];
     }
     else {
      var newObj = propNested.shift();
        return getProperty(obj[newObj], propNested);
     }
    };
    var sort = function (prop, arr) {
        arr.sort(function (a, b) {
                    var aProp = getProperty(a, prop.split("."));
                    var bProp = getProperty(a, prop.split("."));
            if (aProp < bProp) {
                return -1;
            } else if (aProp > bProp) {
                return 1;
            } else {
                return 0;
            }
        });
    };
    
    0 讨论(0)
  • 2020-12-01 07:04

    Use Array.prototype.sort() with a custom compare function to do the descending sort first:

    champions.sort(function(a, b) { return b.level - a.level }).slice(...
    

    Even nicer with ES6:

    champions.sort((a, b) => b.level - a.level).slice(...
    
    0 讨论(0)
提交回复
热议问题