views:

46

answers:

4

Say I have an array: [0,3,4,2,5,1] What i want to do is sort an array such as: ["one", "two", "three", "four", "five", "six"] so that the order corresponds to the first array. This would be the output: ["one", "four", "five", "three", "six", "two"]

Is there an easy way to accomplish this?

+4  A: 

You can do something like this:

function getSorted(arr, sortArr) {
  var result = [];
  for(var i=0; i<arr.length; i++) {
    result[i] = arr[sortArr[i]];
  }
  return result;
}

You can test it out here.

Note: this assumes the arrays you pass in are equivalent in size, you'd need to add some additional checks if this may not be the case.

Nick Craver
Thanks Nick, this works perfectly!
A: 

If the numbers are only from 0 to 9 then it's easy.

var input = [0,3,4,2,5,1];

function order(input) {
   var numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
   var result = [];
   for (var i in input) {
      result[i] = numbers[input[i]];
   }
   return result;
}

var result = order(input);

alert(result.join(" ")); // returns "zero three four two five one"

But if you want to go with 10s, 1000s, 10000s and so on, then there's no general solution because the the orders have no upper limit and literal names run out.

Saul
A: 

Not sur how you get your first array, but you could use an array of objects instead of [0,3,4,2,5,1]:

var arr = [
  {n:0, s:'one'},
  {n:3, s:'four'},
  {n:4, s:'five'},
  {n:2, s:'three'},
  {n:5, s:'six'},
  {n:1, s:'two'}
]

And avoid to process it.

Mic
A: 
orderedArray= function(arr,order){
    return  order.map(function(itm){return arr[itm]});
}

var sequence= [0, 3, 4, 2, 5, 1],arr=["one","two","three","four","five","six"]

arr=new orderedArray(arr,sequence);

/*  returned value: (Array)
one,four,five,three,six,two
*/

//You can make the order an unindexed property of the array, // and call array.ordered()

Array.prototype.ordered= function(order){
    var arr= this;
    order=order || this.order;
    return order.map(function(itm){
        return arr[itm];
    });
}


var arr= ["one","two","three","four","five","six"],
sequence= [0, 3, 4, 2, 5, 1];

arr.order=sequence;

arr.ordered()

/*  returned value: (Array)
one,four,five,three,six,two
*/
kennebec