简体   繁体   中英

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:

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)

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. 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.

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. 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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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