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>
- 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.
-
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.
- We push each element into the appropriate subarray using the push() method.
- Finally, we log the resulting array of subarrays to the console.
save
listen
AI Answer
How to create multiple array from single array
0
To convert a single array into multiple arrays, you can use a loop and push elements into…
asked
Apu
0 answers
2915
To convert a single array into multiple arrays, you can use a loop and push elements into…
Answer Link
answered
Apu