rearrange Array according to values order of another Array
        Posted  
        
            by 
                Exception
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Exception
        
        
        
        Published on 2013-11-01T02:57:22Z
        Indexed on 
            2013/11/01
            3:54 UTC
        
        
        Read the original article
        Hit count: 161
        
JavaScript
I have two arrays like below
  var arr = ["x", "y", "z", "a", "b", "c"];
  var tgtArr = [{val:"a"}, {val:"b"}]; It does not need to be as lengthy as Array `arr`
This is what I have tried
  var dest = new Array(arr.length);
  for(var i = 0; i < arr.length; i++){
      for(var k = 0; k < tgtArr.length; k++){
          dest[i] = dest[i] || [];
          if(tgtArr[k].val == arr[i]){
              dest[i] = arr[i];
          }
      }
  }
  console.log(dest);
My Expected output is  (for above tgtArr value)   
  [{}, {}, {}, {val:"a"}, {val:"b"}, {}];
if tgtArr is empty Array 
  [{},{},{},{},{},{}]      
Here is the fiddle. Any alternative for this, it seems not a good way to me as I am iterating through the entire array everytime.
© Stack Overflow or respective owner