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?
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.
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
*/
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