title: How to rearrange array in place using loop
body: <p>I have this array <code>[-1, 8, -1, 6, -1, 4, -1, 2, 0, -1]</code></p>
  <p>I want to rearrange in place using the loop, where the element will place in its index</p>
  <p>For example, element 8 will be placed in the 8th index, element 0 will be in the 0th index</p>
  <p>output <code>[0,-1,2,-1,4,-1,6,-1,8,-1]</code>;</p>
  <p>This is my code</p>
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>let arr = [-1, 8, -1, 6, -1, 4, -1, 2, 0, -1];
  
  for (let i = 0; i &lt; arr.length; i++) {
    const elem = arr[i];
    // console.log('---',elem)
    if (i !== arr[i]) {
      if (arr[i] !== -1) {
  
        const valInd = arr[arr[i]];
        arr[arr[i]] = elem;
        arr[i] = valInd
      }
    }
  
  };
  
  console.log(arr);</code></pre>
  </div>
  </div>
  </p>
  <p>Please help me understand where I am missing</p>