js sort() custom function how can i pass more parameters?

后端 未结 4 1257
醉梦人生
醉梦人生 2020-12-15 10:55

I have an array of objects i need to sort on a custom function, since i want to do this several times on several object attributes i\'d like to pass the key name for the att

4条回答
  •  我在风中等你
    2020-12-15 11:36

    Yes, have the comparator returned from a generator which takes a param which is the key you want

    function compareByProperty(key) {
        return function (a, b) {
            a = parseInt(a[key], 10);
            b = parseInt(b[key], 10);
            if (a < b) return -1;
            if (a > b) return 1;
            return 0;
        };
    }
    arrayOfObjects.sort(compareByProperty('myKey'));
    

    compareByProperty('myKey') returns the function to do the comparing, which is then passed into .sort

提交回复
热议问题