给定一组对象:
{ key: "a", value: 42 }, { key: "d", value: 28 }, { key: "c", value: 92 }, { key: "b", value: 87 }
和一系列键:
["c", "a", "b", "d"]
是否有ECMAScript函数或第三方JavaScript库允许您排序 - 在一行/函数调用 - 第一个对象数组,以匹配键的顺序在第二个数组中指定,结果为:
{ key: "c", value: 92 }, { key: "a", value: 42 }, { key: "b", value: 87 }, { key: "d", value: 28 }
提供功能或算法的其他问题:
相似/相关问题:
答案 0 :(得分:40)
只需使用indexOf
将密钥转换为正确的顺序:
var order = ["c", "a", "b", "d"];
_.sortBy(arr, function(obj){
return _.indexOf(order, obj.key);
});
如果有很多键,那么从数组中制作哈希映射会更有利,例如:
var order = ["c", "a", "b", "d"];
var orderMap = {};
_.each(order, function(i) { orderMap[i] = _.indexOf(order, i); });
这使得键排序查找恒定时间而不是O(n)。 (Fiddle)
答案 1 :(得分:18)
到目前为止提供了很好的答案。认为以下也可能是普通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 ) );
答案 2 :(得分:2)
我无法声称这是大多数有效方式,但您可以将key
用作每个对象作为另一个对象中属性的键。然后只需通过这些键访问它们。
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);
答案 3 :(得分:1)
const obj = [
{
key: "a",
value: 42
},
{
key: "d",
value: 28
},
{
key: "c",
value: 92
},
{
key: "b",
value: 87
}
]
const sortList = ["c", "a", "b", "d"];
const sortedObj = obj.sort((a, b) => {
return (
sortList.indexOf(a.key) - sortList.indexOf(b.key)
);
});
console.log(sortedObj );
答案 4 :(得分:0)
// 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])