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?
First of all I’d like to note that
newis a keyword that should probably be avoided as a variable name.jQuery’s
mapwill 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:
That should reorder
oldArrayto['b', 'd', 'a', 'c']. However, you’re still replacingoldArraywith 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.