我有两个这样的对象数组
var array1 = [
{
"key": 0,
"display": "hide",
},
{
"key": 1,
"display": "show",
},
{
"key": 2,
"display": "show",
},
]
var array2 = [
{
"key": 1,
"question": "some text here",
},
{
"key": 0,
"question": "Different text here",
},
{
"key": 2,
"question": "Even more different",
},
]
我需要重新排序array1以匹配array2中键的顺序,而不仅仅是更新键以匹配顺序,但显示值需要更新(因此移动/重新排序整个对象)
例如,在对array1进行排序以匹配array2键的顺序后,我希望array1导致:
[
{
"key": 1,
"display": "show",
},
{
"key": 0,
"display": "hide",
},
{
"key": 2,
"display": "show",
}
]
我知道这可能是使用sort函数完成的,但是我很难理解它在这种情况下是如何工作的。
答案 0 :(得分:2)
您可以创建一个hashMap,它将保存索引值,并根据它来排序数组。
var array1 = [ { "key": 0, "display": "hide", }, { "key": 1, "display": "show", }, { "key": 2, "display": "show", },]
var array2 = [ { "key": 1, "question": "some text here", }, { "key": 0, "question": "Different text here", }, { "key": 2, "question": "Even more different", },]
var array2Hash = array2.reduce(function(p,c,i){
p[c.key] = i;
return p;
}, Object.create(null))
array1.sort(function(a,b){
return array2Hash[a.key] - array2Hash[b.key];
});
console.log(array1);
答案 1 :(得分:2)
您可以通过以下方式实现这一目标:
var array1 = [ { "key": 0, "display": "hide", }, { "key": 1, "display": "show", }, { "key": 2, "display": "show", }];
var array2 = [ { "key": 1, "question": "some text here", }, { "key": 0, "question": "Different text here", }, { "key": 2, "question": "Even more different", }];
var keys = array2.map(el => el.key);
array1.sort((a, b) => keys.indexOf(a.key) - keys.indexOf(b.key));
console.log(array1);
答案 2 :(得分:1)
我可能通过构建第一个数组索引的键映射来接近它,然后在排序第二个数组时使用该映射,请参阅注释:
var array1 = [ { "key": 0, "display": "hide", }, { "key": 1, "display": "show", }, { "key": 2, "display": "show", },]
var array2 = [ { "key": 1, "question": "some text here", }, { "key": 0, "question": "Different text here", }, { "key": 2, "question": "Even more different", },]
// Build the map of key->index from the first array
var map = Object.create(null);
array1.forEach(function(entry, index) {
map[entry.key] = index;
});
// Sort the second array using the key->index map
// map[left.key] - map[right.key] returns a number less than 0
// if the left should be before the right, 0 if they're the
// the same (they won't be, as these are indexes from the
// first array), or greater than zero if the left should be
// after the right
array2.sort(function(left, right) {
return map[left.key] - map[right.key];
});
console.log(array2);

.as-console-wrapper {
max-height: 100% !important;
}