title: Change elements positions in an array and shift elements in between
body: <p>I would like to pick an element in an array, move it to another index, and then "shift/rotate" the "in-between" elements by 1.</p>
  
  <p>Imagine a drag and drop functionality, if the index <code>from</code> is less than index <code>to</code>, then I would like to shift to be to the left, and else shift to be to the right.</p>
  
  <p><strong>Input:</strong></p>
  
  <p><code>let data = [ 0, 1, 2, 3, 4, 5, 6 ]</code></p>
  
  <p><strong>Task1:</strong>
  <code>insertAndShift(data, 0, 3): Take element at index 0, shift indexes 1, 2, 3 to the left, and then insert index 0 at 3</code></p>
  
  <p><strong>Expected Output:</strong></p>
  
  <p><code>[ 1, 2, 3, 0, 4, 5, 6 ]</code></p>
  
  <p><strong>Task2:</strong> 
  <code>insertAndShift(data, 3, 0) Take element at index 3, shift indexes 0, 1, 2 to the right and then insert index 3 at 0</code></p>
  
  <p><strong>Expected Output:</strong></p>
  
  <p><code>[ 0, 1, 2, 3, 4, 5, 6 ]</code></p>
  
  <p>I tried this:</p>
  
  <p>Following <a href="http://geniuscarrier.com/rotating-an-array-in-place-javascript/" rel="noreferrer">Rotating an array in place</a>, ugly and not working code (temp always undefined + result is not complete + possible work only for RIGHT):</p>
  
  <pre><code>insertAndShift(data, from, to)
  {
      if(from &lt; to)
      {
          // rotate in between - LEFT
  
      }
      else
      {    
          // swap elements
          let temp = data[from];
          data[from] = data[to];
          data[to] = temp;
  
          // rotate in between - RIGHT
          let newData = this.rotate(data.slice(to, from - 1), 1)
  
          let result = [];
          result.push(data.slice(0,1));
          newData.map((element) =&gt; result.push(element))
          for(let i = from+1; i &lt; data.length; i++)
          {
              result.push(data[i]);
          }
  
          this.setState({data: result})
      }
  }
  
  rotate(arr, k) {
      var l = arr.length;
      arr = this.reverseArr(arr, 0, l - 1);
      arr = this.reverseArr(arr, 0, k - 1);
      arr = this.reverseArr(arr, k, l - 1);
      return arr;
  }
  
  reverseArr(arr, left, right) {
      while (left &lt; right) {
          var temp = arr[left];
          arr[left] = arr[right];
          arr[right] = temp;
          left++;
          right--;
      }
      return arr;
  }
  </code></pre>
  
  <p>Also following <a href="https://stackoverflow.com/questions/20468751/javascript-dynamic-insert-into-array-then-shift-all-elements-underneath-1">Javascript (dynamic) insert into array, then shift all elements underneath +1</a>, which returns only 1 item:</p>
  
  <pre><code>else
  {
      let result = data.splice(to, 1, data[from]);
      this.setState({allTasksArray: result})
  }
  </code></pre>
  
  <p>How can I achieve this for both Left and Right?</p>