2

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?

emil
  • 1,642
  • 13
  • 12
user544079
  • 16,109
  • 42
  • 115
  • 171
  • There is a `sort` method in JavaScript...What's the purpose of this? Do the arrays contains the same data just different order? – elclanrs Feb 02 '13 at 22:34
  • 1
    Yes: http://stackoverflow.com/questions/7365814/in-place-array-reordering Why you want to do this though is beyond me :). – Reck Feb 02 '13 at 22:38
  • I know you already have to possible answers, but could you give examples of what both arrays look like? – bfavaretto Feb 02 '13 at 22:48
  • Well, in theory you can force-sort an array, based on another one, with [Schwartzian transform](http://en.wikipedia.org/wiki/Schwartzian_transform) technique... But I actually consider the approach followed in the question superior to this. ) – raina77ow Feb 02 '13 at 23:15
  • I don't want to put this as an answer because it seems so pointless, but you could add the values to the end of the old array -- `old.push(old[new[i]])` -- and then at the end of the function chop out the original values -- `old.splice(0, new.length);` (so the array will be altered in-place rather than returning a new array) – Stuart Feb 02 '13 at 23:32

1 Answers1

1

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.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
redbmk
  • 4,687
  • 3
  • 25
  • 49
  • 1
    There's a subtle difference between [.map](http://api.jquery.com/map/) and [$.map](http://api.jquery.com/jQuery.map/): the former returns a jQuery object, not an Array. And yes, sometimes it _will_ bite you - like when you attempt to serialize its results, for example. – raina77ow Feb 02 '13 at 23:06
  • Oops! Thanks for catching that. – redbmk Feb 02 '13 at 23:16