Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array in the same order of another array

I have a few arrays of 50+ names like this.

["dan", "ryan", "bob", "steven", "corbin"]
["bob", "dan", "steven", "corbin"]

I have another array that has the correct order. Note that the second array above does not include all of the names, but I still want it to follow the order of the following:

["ryan", "corbin", "dan", "steven", "bob"]

There is no logical order to it, they are just in this order. What makes sense to me is to compare each array against the correctly ordered one. I think I saw some people doing this with PHP, but I was not able to find a JavaScript solution. Does anyone have any idea how to do this? I've been trying for a few hours and I'm stumped.

like image 553
barry Avatar asked Feb 07 '15 01:02

barry


People also ask

How do I sort two arrays in the same order?

Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list.

How do you sort an array in a specific order?

sort((a,b) => { if ( a.name < b.name ){ return -1; } if ( a.name > b.name ){ return 1; } return 0; }); And it is trivial enough to swap the sort order by switching the returns or the if statements above.

How do you sort an array and assign it to another array in Java?

You can sort within the array using Arrays. sort() method, or if you want to sort in a different array, you can take following steps: Copy the array to new array. Sort the new array and then sort.


1 Answers

Use indexOf() to get the position of each element in the reference array, and use that in your comparison function.

var reference_array = ["ryan", "corbin", "dan", "steven", "bob"];
var array = ["bob", "dan", "steven", "corbin"];
array.sort(function(a, b) {
  return reference_array.indexOf(a) - reference_array.indexOf(b);
});
console.log(array); // ["corbin", "dan", "steven", "bob"]

Searching the reference array every time will be inefficient for large arrays. If this is a problem, you can convert it into an object that maps names to positions:

var reference_array = ["ryan", "corbin", "dan", "steven", "bob"];
reference_object = {};
for (var i = 0; i < reference_array.length; i++) {
    reference_object[reference_array[i]] = i;
}
var array = ["bob", "dan", "steven", "corbin"];
array.sort(function(a, b) {
  return reference_object[a] - reference_object[b];
});
console.log(array);
like image 57
Barmar Avatar answered Oct 30 '22 10:10

Barmar