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

后端 未结 8 1847
广开言路
广开言路 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条回答
  •  Happy的楠姐
    2020-12-01 06:59

    You can split the prop on ., and iterate over the Array updating the a and b with the next nested property during each iteration.

    Example: http://jsfiddle.net/x8KD6/1/

    var sort = function (prop, arr) {
        prop = prop.split('.');
        var len = prop.length;
    
        arr.sort(function (a, b) {
            var i = 0;
            while( i < len ) { a = a[prop[i]]; b = b[prop[i]]; i++; }
            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            } else {
                return 0;
            }
        });
        return arr;
    };
    

提交回复
热议问题