Logo Questions Linux Laravel Mysql Ubuntu Git Menu

sort array of ints based on another array of ints

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];
like image 772
frenchie Avatar asked Dec 25 '22 13:12


1 Answers

Try this:

ArrayToSort.sort(function(x, y) {
    return SortedArray.indexOf(x) - SortedArray.indexOf(y);


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.

like image 140
p.s.w.g Avatar answered Dec 28 '22 01:12