Suppose I have two arrays, like this:
var SortedArray = [25, 123, 2464, 112, 54, 51, 347, 4572, 634];
var ArrayToSort = [634, 25, 51, 123];
SortedArray
is an array that contains the order of many elements. ArrayToSort
contains just some of the elements of SortedArray
and every element in ArrayToSort
is certain to also be in SortedArray
.
What's the best way to sort ArrayToSort so that the elements in that array appear in the same order as SortedArray and get this result:
ArrayToSort = [25, 123, 51, 634];
Try this:
ArrayToSort.sort(function(x, y) {
return SortedArray.indexOf(x) - SortedArray.indexOf(y);
});
Demonstration
Note: using this method, if an element does not appear in SortedArray
, it will be placed before all other elements that are found in SortedArray
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With