Sort an array based on another array of integers
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
*/
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.