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

后端 未结 5 1470
渐次进展
渐次进展 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条回答
  •  粉色の甜心
    2021-01-20 00:13

    You could iterate the keys and use Array#some for getting the order value.

    This proposal works with a short circuit, if a delta is truthy (!== 0), then the iteration breaks and the delta is returned to the sort callback.

    function sortByThenBy(array, keys) {
        return array.sort(function (a, b) {
            var r = 0;
            keys.some(function (k) {
                return r = a[k] - b[k];
            });
            return r;
        });
    }
    
    var items = [{ name: "AA", prop1: 12, prop2: 13, prop3: 5, prop4: 22 }, { name: "AA", prop1: 12, prop2: 13, prop3: 6, prop4: 23 }, { name: "AA", prop1: 12, prop2: 14, prop3: 5, prop4: 23 }, { name: "AA", prop1: 11, prop2: 13, prop3: 5, prop4: 22 }, { name: "AA", prop1: 10, prop2: 13, prop3: 9, prop4: 21 }];
    
    console.log(sortByThenBy(items, ["prop1", "prop3", "prop4"]));
    console.log(sortByThenBy(items, ["prop1", "prop3"]));
    console.log(sortByThenBy(items, ["prop3", "prop1", "prop4"]));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题