Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu April 10, 2023 › #Array #HowTo

How to create multiple array from single array

To convert a single array into multiple arrays, you can use a loop and push elements into each subarray based on their index.

The example is given below.

<script>
 let myArray = [1,2,3,4,5,6,7,8,9];
 let subArrays = [[],[],[],[],[]]; 

 for(let i = 0; i < myArray.length; i++) {
  subArrays[i % 5].push(myArray[i]); 
 }

 console.log(subArrays); // output : [[1, 6],[2, 7],[3, 8],[4, 9],[5]]

</script>
  1. We start by creating an array of empty subarrays with a length of 5, as we want to split the original array into 5 subarrays.
  2. We loop through each element in the original array and use the modulo operator (%) to determine which subarray it should be pushed to.

    The modulo operator returns the remainder of a division operation - in this case, i % 5 will return 0, 1, 2, 3, or 4, which corresponds to the index of a subarray.

  3. We push each element into the appropriate subarray using the push() method.
  4. Finally, we log the resulting array of subarrays to the console.
save
listen
AI Answer
Write Your Answer
loading
back
View All