试图弄清楚。不行我有2个数组,我想对其中一个的索引进行排序,以使其对象匹配该索引。
数组1仍然存在:
var arr1 = [
{
"name": "bobby",
"occupation": "singer"
},
{
"name": "mindy",
"occupation": "artist"
}
]
和数组2:
var arr2 = [
{
"name": "mindy",
"hobby": "drawing"
},
{
"name": "bobby",
"hobby": "driving"
}
]
哪一个重新建立索引并不重要。关键是我有两个名称bobby
和mindy
,我想重新排列这些数组中的一个,使它们的索引与另一个匹配。
答案 0 :(得分:5)
将sort
与compareFunction一起使用。
在下面找到嵌入式注释。
var arr1 = [
{
"name": "bobby",
"occupation": "singer"
},
{
"name": "mindy",
"occupation": "artist"
}
]
var arr2 = [
{
"name": "mindy",
"hobby": "drawing"
},
{
"name": "bobby",
"hobby": "driving"
}
]
// create intermediate array of arr2 names
arr2Names = arr2.map(x => x.name)
// use sort:
arr1 = arr1.sort((x,y) => arr2Names.indexOf(x.name) - arr2Names.indexOf(y.name))
console.log(arr1, arr2)
var arr2 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
var arr1 = ['b', 'd', 'g', 'f', 'e', 'a', 'c']
console.log(arr1.sort((x,y) => arr2.indexOf(x) - arr2.indexOf(y)))
答案 1 :(得分:2)
通常的(?)简短版本是O(n 2 )(假设所有名称都是唯一的,并且在两个数组中都存在):
var arr1 = [ { "name": "bobby", "occupation": "singer" },
{ "name": "mindy", "occupation": "artist" } ];
var arr2 = [ { "name": "mindy", "hobby": "drawing" },
{ "name": "bobby", "hobby": "driving" } ];
var arr2 = arr1.map(a => arr2.find(b => a.name === b.name));
console.log( JSON.stringify(arr1).replace('},', '},\n ') );
console.log( JSON.stringify(arr2).replace('},', '},\n ') );
按名称对两个数组进行排序是O(n log n):
var arr1 = [ { "name": "bobby", "occupation": "singer" },
{ "name": "mindy", "occupation": "artist" } ];
var arr2 = [ { "name": "mindy", "hobby": "drawing" },
{ "name": "bobby", "hobby": "driving" } ];
arr1.sort((a, b) => a.name.localeCompare(b.name));
arr2.sort((a, b) => a.name.localeCompare(b.name));
console.log( JSON.stringify(arr1).replace('},', '},\n ') );
console.log( JSON.stringify(arr2).replace('},', '},\n ') );
最后,使用查找帮助程序对象创建O(n)版本:
var arr1 = [ { "name": "bobby", "occupation": "singer" },
{ "name": "mindy", "occupation": "artist" } ];
var arr2 = [ { "name": "mindy", "hobby": "drawing" },
{ "name": "bobby", "hobby": "driving" } ];
var lookup = arr2.reduce((r, v) => (r[v.name] = v, r), {});
var arr2 = arr1.map(v => lookup[v.name]);
console.log( JSON.stringify(arr1).replace('},', '},\n ') );
console.log( JSON.stringify(arr2).replace('},', '},\n ') );