jQuery 按特定顺序对 JavaScript 对象数组进行排序(使用现有函数)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18859186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:38:13  来源:igfitidea点击:

Sorting an Array of JavaScript Objects a Specific Order (using existing function)

javascriptjqueryarrayssortingunderscore.js

提问by mkopala

Given an array of objects:

给定一组对象:

{
    key: "a",
    value: 42
},
{
    key: "d",
    value: 28
},
{
    key: "c",
    value: 92
},
{
    key: "b",
    value: 87
}

and an array of keys:

和一组键:

["c", "a", "b", "d"]

Is there a ECMAScript function or a 3rd-party JavaScript library that lets you sort - in one line/function call- the first array of objects, to match the order of the keysspecified in the second array, such that the result is:

是否有 ECMAScript 函数或第 3 方 JavaScript 库可以让您在一行/函数调用中对第一个对象数组进行排序,以匹配第二个数组中指定的键的顺序,结果是:

{
    key: "c",
    value: 92
},
{
    key: "a",
    value: 42
},
{
    key: "b",
    value: 87
},
{
    key: "d",
    value: 28
}

Other questions that provide a function or algorithm:

提供函数或算法的其他问题:

Similar/related questions:

类似/相关问题:

回答by McGarnagle

Just use indexOfto convert the key to the correct order:

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

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

Fiddle

小提琴

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

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

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

回答by PeterKA

Great answers provided so far. Thought that the following may also be an alternative solution in plain JS:

到目前为止提供了很好的答案。认为以下也可能是纯JS中的替代解决方案:

var arr = arr.sort(function(a,b) {
    return order.indexOf( a.key ) > order.indexOf( b.key );
    //for the sake of recent versions of Google Chrome use:
    //return a.key.charCodeAt(0) > b.key.charCodeAt(0); or return a.key.charCodeAt(0) - b.key.charCodeAt(0);
});

var arr = [
    {
        key: "a",
        value: 42
    },
    {
        key: "d",
        value: 28
    },
    {
        key: "c",
        value: 92
    },
    {
        key: "b",
        value: 87
    }
];

var order = ["c", "a", "b", "d"];

console.log( 'Original: ', JSON.stringify( arr ) );

var arr = arr.sort(function(a,b) {
      return order.indexOf( a.key ) > order.indexOf( b.key );
});

console.log( 'Ordered: ', JSON.stringify( arr ) );

回答by Explosion Pills

I can't claim that this is the mostefficient way, but you can use the keyfor each object as a key for properties in another object. Then simply access them by these keys.

我不能说这是有效的方法,但是您可以将keyfor each 对象用作另一个对象中属性的键。然后只需通过这些键访问它们。

for (x = 0; x < objn.length; x++) {
    newobj[objn[x].key] = objn[x];
}
objn = [];
for (x = 0; x < keys.length; x++) {
    objn.push(newobj[keys[x]]);
}
console.log(objn);

http://jsfiddle.net/WdehF/

http://jsfiddle.net/WdehF/

回答by Josmar

// create hash map el.key -> index, to help us with direct access, avoid searching
const hashMap = arr.reduce((acc, el, index) => { acc[el.id] = el; return acc }, {})

// finally, map the ids to the final result
const ids.map(id => hashMap[id])