Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an Array according to the order of another Array

I have an array with sizes like this:

var arr = [
  'small',
  'small',
  'small',
  'small',
  ...
  'medium',
  'medium',
  'medium',
  'medium',
  ...
  'big',
  'big',
  ...
];

I need to reorganize this array according to this order:

var order = ['small', 'small', 'medium', 'medium', 'big'];

So the result ends up being something like this:

var arr = [
  'small',
  'small',
  'medium',
  'medium',
  'big',

  'small',
  'small',
  'medium',
  'medium',
  'big'

  ...
];

I'm aware of other similar questions in SO but I couldn't find anything so far. I'm unsure how to approach this. I was thinking sort should do but what do I test for? It seems simple but I'm stuck, don't know where to begin. Any hints?

like image 830
elclanrs Avatar asked Mar 21 '13 05:03

elclanrs


1 Answers

Just define a scorer for your sort method. Here is your code. Try it

var init_arr = ['small', 'big', 'big', 'medium'];

var scorer = {
   small: 0,
   medium: 1,
   big: 2
}

// You can use the same array too. I am creating new one.
var final_arr = init_arr.sort(function(a,b) {
   return scorer[a]-scorer[b];
});

alert(final_arr); //small, medium, big, big

Working Fiddle

like image 200
Sachin Avatar answered Oct 13 '22 05:10

Sachin