ScriptsConnect ScriptsConnect - 5 months ago 26
jQuery Question

How to sort array data using another array as a template?

I'm trying to sort a dynamically generated JavaScript array against a 'master' array. This master array is to be used as the template for how to sort the dynamically generated array. The master array, however, may have new items added in the future, but such items would be added manually.

The array that needs to be sorted is:

var arrayToSort = ['ABCD','ABCD 123 Team','IMT_User_MNOP'];


The master array is:

var roleDef = ['IMT_User_MNOP','IMT_User_User','ABCD','ABCD 123 Team','ABCD Plans'];


I've browsed nearly all solutions here at SO, and none of them deal with sorting an array against another array based on having a non-matching number of items and sorting the index value
===
index value. And other solutions deal with keys, or sorting numbers based on letters (or letters based on numbers), etc.

I appreciate any help someone can provide, even if it is just to point me in the right direction so I can figure this out.

Answer

var arrayToSort = ['ABCD','ABCD 123 Team','IMT_User_MNOP'];
var roleDef = ['IMT_User_MNOP','IMT_User_User','ABCD','ABCD 123 Team','ABCD Plans'];


var newArr = arrayToSort.map(function(item){
  var idx = roleDef.indexOf(item);
  
  return {
    val:item,
    roleDefIndex:idx
  };
});
var result = newArr.sort(function(a, b) {
  return a.roleDefIndex - b.roleDefIndex;
}).map(function(item){
  return item.val;
});
console.log(result);

Other version

var arrayToSort = ['ABCD','ABCD 123 Team','IMT_User_MNOP'];
var roleDef = ['IMT_User_MNOP','IMT_User_User','ABCD','ABCD 123 Team','ABCD Plans'];

var IndexWithinRole = {};
 arrayToSort.forEach(function(item){
  IndexWithinRole[item] = roleDef.indexOf(item);
});
arrayToSort.sort(function(a, b) {
  return IndexWithinRole[a] - IndexWithinRole[b];
});
console.log(arrayToSort);