且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

排序的JavaScript对象的数组(使用现有的功能)的特定顺序

更新时间:2023-10-30 14:53:16

只需使用的indexOf 将密钥转换为正确的顺序:

Just use indexOf to convert the key to the correct order:

var order = ["c", "a", "b", "d"];
_.sortBy(arr, function(obj){ 
    return _.indexOf(order, obj.key);
});

小提琴

如果有很多键,那么这将是有利的,使散列映射出的数组,如:

If there are a lot of keys, then it would be advantageous to make a hash-map out of the array, like:

var order = ["c", "a", "b", "d"];
var orderMap = {};
_.each(order, function(i) { orderMap[i] = _.indexOf(order, i); });

这使得键排序查找固定的时间,而不是为O(n)。 (小提琴

This makes the key-sorting lookup constant time rather than O(n). (Fiddle)