简体   繁体   English

基于另一个数组排序数组(对象的更改顺序)

[英]Sort array based on another array (change order of objects)

I have two Javascript array objects, where first one is sorted in the order I want it to be sorted in and second array is sorted in the wrong order, for example: 我有两个Javascript数组对象,其中第一个按照我希望它排序的顺序排序,第二个数组按错误的顺序排序,例如:

1) SortedArray (0 - 10 items, 11 - 20 items, 21 - 30 items, 10000 - 20000 items) 1)SortedArray (0 - 10 items, 11 - 20 items, 21 - 30 items, 10000 - 20000 items)

2) Alphabetically sorted Array (0 - 10 items, 10000 - 20000 items, 11 - 20 items, 21 - 30 items) 2)按字母顺序排序的数组(0 - 10 items, 10000 - 20000 items, 11 - 20 items, 21 - 30 items)

I would like to sort the second array in the same order as the first one, is there an easy way to solve this issue? 我想按照与第一个数组相同的顺序对第二个数组进行排序,是否有一种简单的方法可以解决这个问题?

Any help would be appreciated. 任何帮助,将不胜感激。 Thank you. 谢谢。

Conditions: 条件:

1) The second array can be different in size. 1)第二阵列的大小可以不同。 So it could have less values than the first array. 所以它的值可能比第一个数组少。

2) If the data is corrupt, the second array can have values that do not exist in the first array. 2)如果数据损坏,第二个数组可以具有第一个数组中不存在的值。

Update 更新

I have built an sample here based on Bergi's response: jsfiddle.net/EPwS6 - but now I need to figure out how I can preserve values in arr2 which do not exist in arr1. 我根据Bergi的响应在这里构建了一个示例:jsfiddle.net/EPwS6 - 但现在我需要弄清楚如何在arr2中保存arr1中不存在的值。 Any ideas or tips? 任何想法或提示?

If both arrays contain the same items, but in different order, it's easy: Just copy the first array to the second. 如果两个数组包含相同的项目,但顺序不同,则很容易:只需将第一个数组复制到第二个数组即可。 Either use a direct reference, or slice to create a new array. 使用直接引用或slice来创建新数组。

If the two arrays contain different objects with similar keys, it gets more difficult. 如果两个数组包含具有相似键的不同对象,则会变得更加困难。 Yet you can easily manage that by creating a lookup table: 然而,您可以通过创建查找表轻松管理它:

var table = {};
for (var i=0; i<arr2.length; i++)
    table[ arr2[i].getKey() ] = arr2[i];
for (var i=0; i<arr1.length; i++)
    arr2[i] = table[ arr1[i].getKey() ];
table = null;
// arr2 now ordered by the same keys as arr1, and its length is set to arr1.length

If the key sets are not the same, you might go with something like this: 如果密钥集不相同,您可能会使用以下内容:

var table = {};
for (var i=0; i<arr2.length; i++)
    table[ arr2[i].getKey() ] = arr2[i];
for (var i=0; i<arr1.length; i++) {
    var key = arr1[i].getKey();
    if (key in table) {
        arr2.push(table[key]); // add to array
        delete table[key]; // and prevent readding
    }
}
for (var key in table)
    arr2.push(table[key]); // add all leftover objects
table = null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM