How to sort an array of objects with multiple field values in JavaScript

前端 未结 5 1885
迷失自我
迷失自我 2020-12-10 13:56

I found a great method to sort an array of objects based on one of the properties as defined at:

Sort array of objects by string property value in JavaScript

5条回答
  •  佛祖请我去吃肉
    2020-12-10 14:29

    Here is my solution. It faster than lodash's _.sortBy() multi-column sort function in about two times (see http://jsperf.com/multi-column-sort. I generate text of sorting function, then use it in standard .sort(). It works in Chrome and Firefox as well.

    function multiColumnSort(arr,sf) {
        var s = '';
        sf.forEach(function(f,idx) {
            s += 'if(arguments[0].'+f+'>arguments[1].'+f+')return 1;';
            s += 'else if(arguments[0].'+f+'==arguments[1].'+f+')';
            s += (idx < sf.length-1)? '{' : 'return 0';
        });
        s += Array(sf.length).join('}')+';return -1';
        return arr.sort(new Function(s));
    };
    

提交回复
热议问题