title: javascript - create multidimensional array with elements in array
body: <p>I need to generate a multidimensional array from a multidimensional array. <br>
  For example, my array:</p>
  
  <pre><code>var codes = [
  
  ['2', '12521', '3'],
  ['3', '32344', '2'],
  ['3', '35213', '2'],
  ['4', '42312', '2'],
  ['4', '41122', '1'],
  ['5', '51111', '1']
  
  ];
  </code></pre>
  
  <p>And I need to group the array based on element: For example grouping based on 1st element:</p>
  
  <pre><code>[0] =&gt; Array
      (
          [0] =&gt; Array
              (
                 [0] =&gt; '2'
                 [1] =&gt; '12521'
              }
      )  
  [1] =&gt; Array
      (
          [0] =&gt; Array
              (
                 [0] =&gt; '3'
                 [1] =&gt; '32344'
                 [2] =&gt; '3'
              }
          [1] =&gt; Array
              (
                 [0] =&gt; '3'
                 [1] =&gt; '35213'
                 [2] =&gt; '2'
              }
      )  
  [2] =&gt; Array
      (
          [0] =&gt; Array
              (
                 [0] =&gt; '4'
                 [1] =&gt; '42312'
                 [2] =&gt; '2'
              }
          [1] =&gt; Array
              (
                 [0] =&gt; '4'
                 [1] =&gt; '41122'
                 [2] =&gt; '1'
              }
      )  
  ...
  </code></pre>
  
  <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>var codes = [
  
      ['2', '12521', '3'],
      ['3', '32344', '2'],
      ['3', '35213', '2'],
      ['4', '42312', '2'],
      ['4', '41122', '1'],
      ['5', '51111', '1']
  
  ];
      
  const output = codes.reduce(({result, current}, [x, ...y]) =&gt; {
    if (current !== x) result.push([]);
    result[result.length - 1].push([x, ...y]);
    
    return {result, current: x};
  }, {result: []}).result;
  
  console.log(output);</code></pre>
  </div>
  </div>
  </p>
  
  <p>For the function , i can group based on the 1st element. But what if I need to group based on 2nd , 3rd element, any ways to do it without switching the position of the array elements (for example, not switching 3rd element to the 1st position and run the function)</p>