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?
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
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