Reputation: 16639
Trying to arrange an array based on the order of another array
function Sort(old, new){
var temp = [];
for(var i=0; i<old.length; i++){
temp[i] = old[new[i]];
}
return temp;
}
Is it possible to achieve the same without the use of a temp[]
additional array?
Upvotes: 2
Views: 75
Reputation: 4796
First of all I'd like to note that new
is a keyword that should probably be avoided as a variable name.
jQuery's map
will let you do that, although it's quite possible a temp variable is used internally. The nice thing about that project is that it will continue to improve and even if that function is currently inefficient it might be more efficient later without having to call it a different way.
Here's a one-liner if you're not opposed to using jQuery:
var oldArray = ['a', 'b', 'c', 'd'],
newOrder = [1, 3, 0, 2];
oldArray = jQuery.map(newOrder, function(val) { return oldArray[val]; });
That should reorder oldArray
to ['b', 'd', 'a', 'c']
. However, you're still replacing oldArray
with a new array object. It really depends on what you're trying to accomplish. I don't think you'll be able to fully avoid temporary variables, but there are different solutions depending on whether you're going for simplicity, speed efficiency, memory efficiency, or something else.
Upvotes: 1