Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array based on another array of integers

Let's 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?

like image 776
Sarathi Avatar asked Oct 28 '10 20:10

Sarathi


2 Answers

You can do something like this:

function getSorted(arr, sortArr) {
  var result = [];
  for (var i = 0; i < arr.length; i++) {
    console.log(sortArr[i], arr[i]);
    result[i] = arr[sortArr[i]];
  }
  return result;
}
var arr = ["one", "two", "three", "four", "five", "six"];
var sortArr = [0, 3, 4, 2, 5, 1];
alert(getSorted(arr, sortArr));

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.

like image 123
Nick Craver Avatar answered Sep 29 '22 22:09

Nick Craver


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
*/
like image 40
kennebec Avatar answered Sep 29 '22 21:09

kennebec