I have an array like [1,2,3,4,5,6,7,8,9] and a given number like 6, and I want the result to be like this:
[1,2]
[3,4]
[5,6]
[7]
[8]
[9]
Or if I had number 3:
[1,2,3]
[4,5,6]
[7,8,9]
Or for 4:
[1,2,3]
[4,5]
[6,7]
[8,9]
I have an array like [1,2,3,4,5,6,7,8,9] and a given number like 6, and I want the result to be like this:
[1,2]
[3,4]
[5,6]
[7]
[8]
[9]
Or if I had number 3:
[1,2,3]
[4,5,6]
[7,8,9]
Or for 4:
[1,2,3]
[4,5]
[6,7]
[8,9]
Here is my code:
function splitArray(input, splitNumber){
const arrayLenght = input.length;
if(arrayLenght < splitNumber)
return; //it's not doable :/
const minMembers = Math.floor(arrayLenght / splitNumber);
let remainNumber = arrayLenght - (minMembers*splitNumber);
let i = 0;
for(let j=0; j<splitNumber; j++){
let myArray = [];
for(let i=0; i < minMembers; i++)
myArray.push(input.shift());
if(remainNumber > 0){
myArray.push(input.shift());
remainNumber--;
}
console.log(myArray);
}
}
and calling it:
splitArray([1, 2, 3, 4, 5, 6, 7, 8, 9], 6);