通过动态提供的对象属性列表按顺序排序对象,然后按样式排序 [英] Sort an array of objects by dynamically provided list of object properties in a order by then by style

查看:75
本文介绍了通过动态提供的对象属性列表按顺序排序对象,然后按样式排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写样式为order的泛型排序函数,然后通过按数组提供的属性列表对数组进行排序.

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.

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 }
            ];
// sort by prop1 then by prop3 then by prop4:
var sortedItems = sortByThenBy(items, ["prop1", "prop3", "prop4"]);

// sort by prop1 then by prop3:
var sortedItems = sortByThenBy(items, ["prop1", "prop3"]);

推荐答案

感谢所有出色的回答.作为参考,我发现递归方法也是一种替代解决方案

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));
} 

这篇关于通过动态提供的对象属性列表按顺序排序对象,然后按样式排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆