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

后端 未结 8 1864
广开言路
广开言路 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 06:54

    Would this meet your needs?

    // arr is the array of objects, prop is the property to sort by
    var sort = function (nestedObj, prop, arr) {
        arr.sort(function (a, b) {
            if (a[nestedObj][prop] < b[nestedObj][prop]) {
                return -1;
            } else if (a[nestedObj][prop] > b[nestedObj][prop]) {
                return 1;
            } else {
                return 0;
            }
        });
    };
    

提交回复
热议问题