title: Move Columns Based on Array of Column Numbers
body: <p>I have an array of columns that I want to keep. I've got that code below:</p>
  
  <pre><code>  //Keep only columns user wants.
    if(keepColumnsArray != ""){    
      for (var col = sourceShtLC; col &gt; 0; col--) {
        if (keepColumnsArray.indexOf(col) == -1) {
          // This isn't a keeper, delete it
          destSht.deleteColumn(col);
        }    
      }
    }
  </code></pre>
  
  <p>What I'd like to do now is arrange the columns following the order the <code>keepColumnsArray</code> has them.</p>
  
  <p>Samples:</p>
  
  <pre><code>var keepColumnsArray = [3,2,1,4,5]
  </code></pre>
  
  <p>Using the above sample I want column 3 to be the first column, column 2 to be the second, column 1 to be the 3rd, column 4 to be the 4th and column 5 to be the 5th.</p>
  
  <p>Current Order:</p>
  
  <p><a href="https://i.stack.imgur.com/m6HDu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m6HDu.png" alt="enter image description here"></a></p>
  
  <p>The order I want it. As you can see it's the same order the array is in.</p>
  
  <p><a href="https://i.stack.imgur.com/6CY0l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6CY0l.png" alt="enter image description here"></a></p>
  
  <p>Solution:
  Rather than deleting the columns first I used code from the accepted answer to move the columns I want to keep to the front. In this case Columns 1 through 5 I kept and then I deleted the rest because all that was left were columns I did not need. Here is my final code.</p>
  
  <pre><code>  //Use order of array to reorder columns and then delete the rest of the columns
    var offset = keepColumnsArray.length;
    destSht.insertColumns(1, offset);
    keepColumnsArray.forEach(function(e, i) {
      destSht.getRange(1, (e + offset), destSht.getLastRow(), 1).copyTo(destSht.getRange(1, i + 1));
    });
    destSht.deleteColumns(offset + 1, sourceShtLC);  //Keep only columns user wants.
  </code></pre>