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
sliceto 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:
If the key sets are not the same, you might go with something like this: