There is an array with numbers. For example:

let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; 

How to place them in pairs in a two-dimensional array to get such a two-dimensional array:

 let arr2 = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]; 
  • and the cycle did not try? - Aqua
  • It is possible to cycle through the array first and the number by index of the pair, as in the second array 0.0 0.1 0.2 ... 0, n and unpaired as 1.0 1.1 1.2 ... 1, n - Aqua
  • one
    And what should happen if the initial array has an odd number of elements? - Yaant
  • @Yaant 0 for example - Aqua
  • There is a good universal solution in the English version of SO - Split array into chunks - Lexx918

3 answers 3

 let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; let arr2 = []; for (let i = 0; i < arr.length; i += 2) { if (arr[i] != undefined && arr[i+1] != undefined) { arr2.push([ arr[i], arr[i+1] ]); } } console.log(arr2); 

  • Well, as I said. You know that feeling, when you know the language of the surface, but you know another well, which are similar. The way you know and could not implement. I tried to write the answer)) - Aqua
  • Thank you very much!))) I broke my head over the cycle for two hours. And everything turned out to be very simple. - dvv

Enumerate the keys. Met even? - Created a new nested array for the next pack. In any case, we write the next element in the right pack, and the index is determined by rounding down the key-to-two ratio. Golfman hacks will reduce the code size to:

 let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; let arr2 = []; for (let i = 0; i < arr.length; i++) { !(i % 2) && arr2.push([]); arr2[i / 2 << 0].push(arr[i]); } console.log(arr2); 

  • Reduce the size of the code, but increase the number of cycle passes. - user218976
  • @Anamnian "Premature optimization is the root of all evil" (C) Tony Hoare - Lexx918
  • And here it is? In your case, the number of passes through the cycle corresponds to the number of elements in the array, if there is 1 million elements, the cycle will start a million times. - user218976

If you need to break an array into another number of elements, and not just two at a time:

 const chunkArray = (arr, cnt) => arr.reduce((prev, cur, i, a) => !(i % cnt) ? prev.concat([a.slice(i, i + cnt)]) : prev, []); let sourceArr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; console.log(chunkArray(sourceArr, 2)); console.log(chunkArray(sourceArr, 3)); console.log(chunkArray(sourceArr, 5));