How to sort an array of objects by multiple fields?

后端 未结 30 2358
北恋
北恋 2020-11-21 11:34

From this original question, how would I apply a sort on multiple fields?

Using this slightly adapted structure, how would I sort city (ascending) & then price (

30条回答
  •  长发绾君心
    2020-11-21 12:22

    Simpler one:

    var someArray = [...];
    
    function generateSortFn(props) {
        return function (a, b) {
            for (var i = 0; i < props.length; i++) {
                var prop = props[i];
                var name = prop.name;
                var reverse = prop.reverse;
                if (a[name] < b[name])
                    return reverse ? 1 : -1;
                if (a[name] > b[name])
                    return reverse ? -1 : 1;
            }
            return 0;
        };
    };
    
    someArray.sort(generateSortFn([{name: 'prop1', reverse: true}, {name: 'prop2'}]));
    

提交回复
热议问题