我如何排序的对象基于另一个数组的排序数组?数组、对象

2023-09-12 23:34:34 作者:眼角悲伤的泪

我有对象的列表:

  [{ID:4,名称:亚历克斯},{ID:3,名称:'杰斯'},{ID:9,名称:'...'} {ID:1,名称:'ABC'}]
 

我还有一个列表右侧的命令。

  [3,1,9,4]
 

我如何能在第一个列表匹配第二个列表的顺序,根据关键字身份证? 结果应该是:

  [{ID:3,名称:'杰斯'},{ID:1,名称:'ABC'},{ID:9,名称:'...'} {ID:4,名称:亚历克斯}]
 
java如何一位数组进行排序

解决方案

嗯,简单的答案是,为一组数据这个小,什么比一个无限循环成本更低的将是基本无法察觉的。但是,让我们尝试回答这个正确的。

有没有没头没脑的第二个数组中的顺序,它的外键(用SQL术语)的第一阵列的主键只是一个列表。所以,关心他们的钥匙,而且我们希望这些按键进行有效的查找,哈希表(对象)将很可能之类的这个最快,在 O(N)时装( 2 * N ,真的)假设第一阵列被称作 objArray 与第二阵列被称为 keyArray

  //创建一个临时哈希表来存储对象
变种TEMPOBJ = {};
//重点每个由各自的ID值对象
对于(VAR I = 0; I< objArray.length;我++){
    TEMPOBJ [objArray [I] .ID = objArray [I]
}
//设在keyArray列出的顺序上重建objArray
对于(VAR I = 0; I< keyArray.length;我++){
    objArray [i] = TEMPOBJ [keyArray [I]];
}
//删除临时对象(不能``delete``)
TEMPOBJ =不确定的;
 

和应该这样做。我不认为不需要两遍任何方法。 (任一前一后,像这样的,或者通过阵列通过多次与拼接荷兰国际集团走出找到的元素,它可以得到昂贵的与向后排序的数据,实例。)

I have a list of objects:

[ { id: 4, name:'alex' }, { id: 3, name:'jess' }, { id: 9, name:'...' }, { id: 1, name:'abc' } ]

I have another list with the right "order".

[ 3, 1, 9, 4]

How can I match the first list to the ordering of the second list, based on the key "id"? The result should be:

[ { id: 3, name:'jess' }, { id: 1, name:'abc' }, { id: 9, name:'...' }, { id: 4, name:'alex' } ]

解决方案

Well, the simple answer would be, "for a set of data this small, anything less costly than an infinite loop will be basically unnoticeable." But let's try to answer this "right."

There's no rhyme or reason to the order in the second array, it's just a list of foreign keys (to use SQL terminology) on the primary keys of the first array. So, thinking of them as keys, and that we want efficient lookup of those keys, a hash table (object) would probably "sort" this the quickest, in an O(n) fashion (2*n, really) assuming the first array is called objArray and the second array is called keyArray:

// Create a temporary hash table to store the objects
var tempObj = {};
// Key each object by their respective id values
for(var i = 0; i < objArray.length; i++) {
    tempObj[objArray[i].id] = objArray[i];
}
// Rebuild the objArray based on the order listed in the keyArray
for(var i = 0; i < keyArray.length; i++) {
    objArray[i] = tempObj[keyArray[i]];
}
// Remove the temporary object (can't ``delete``)
tempObj = undefined;

And that should do it. I can't think of any method that doesn't require two passes. (Either one after the other, like this, or by passing multiple times through the array and spliceing out the found elements, which can get costly with backwards-sorted data, for instance.)