Sort an array of objects by dynamically provided list of object properties in a order by then by style

后端 未结 5 1510
渐次进展
渐次进展 2021-01-19 23:42

How to write a generic sorting function in the style orderBy thenBy that sort an array by a list of properties provided as an array.

5条回答
  •  Happy的楠姐
    2021-01-20 00:03

    Thanks for all great answers. For information, I discovered that a recursive approach is also an alternative solution

    function sortByThenBy(items, keys) {
        return items.sort(function(it1, it2){return compare(it1, it2, keys);});
    }
    
    function compare(it1, it2, keys, index) {
        index = index || 0;
        var currentKey = keys[index];
        return it1[currentKey] < it2[currentKey] ? 1 : (it1[currentKey] > it2[currentKey] ? -1 : compare(it1, it2, keys, index + 1));
    } 

提交回复
热议问题