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?

share|improve this question

Your question is confusing, since it has got nothing to do with sorting. You keep the array in the same order, just map each element of the array to an element of another array. – Amnon Oct 28 '10 at 21:20
feedback

4 Answers

up vote 8 down vote accepted

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.

share|improve this answer
Thanks Nick, this works perfectly! – Sarathi Oct 28 '10 at 21:54
feedback

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.

share|improve this answer
feedback
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
*/
share|improve this answer
feedback
class test1
{
  public static String[] sort(int[] array,String[] str)
  {
    String[] out=new String[str.length];
    for(int i=0;i<str.length;i++)
    {
      out[i]=str[array[i]];
    }
    return out;
  }
}
share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.