Reputation: 1
I'm writing a function that takes an array and a number parameter and returns the number amount of arrays split from the given array. So the call chunkArrayInGroups(["a", "b", "c", "d"], 2); should return [a,b] [c,d]. My code is returning [a,c] [b,d]. It should be an easy solution, but I still can't figure out.
function chunkArrayInGroups(arr, size) {
// Break it up.
var newarr=[];
var amount=0;
if(arr.length%2===0)
{
amount=arr.length/size;
}
else
amount=(arr.length/size)+1;
console.log(amount);
for(i=0;i<amount;i++)
{
newarr[i]=[];
}
console.log(newarr);
for(z=0;z<arr.length;z=z+size)
{
for(x=0;x<size;x++)
{
newarr[x].push(arr[z+x]);
}
}
console.log(newarr);
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
Also, if you see bad syntax please correct me, I'm used to writing Java. Thank you!
Upvotes: 0
Views: 94
Reputation: 386570
Beside the given answers, you could use another approach with Array#reduce
and check if you need a new array for a new chunk.
function chunkArrayInGroups(array, size) {
return array.reduce(function(r, a, i, aa) {
i % Math.ceil(aa.length / size) || r.push([]);
r[r.length - 1].push(a);
return r;
}, []);
}
console.log(chunkArrayInGroups(["a", "b", "c", "d", "e"], 3));
Upvotes: 0
Reputation: 26161
This would be my solution;
function chunkArrayInGroups(a,n){
return n > 0 ? n <= a.length ? a.reduce((r,e,i) => (r[Math.floor(n*i/a.length)].push(e),r), Array(n).fill().map(_ => [])) : a : a;
}
var a = ["a", "b", "c", "d","e"],
n = 3;
result = chunkArrayInGroups(a,n);
console.log(result);
Upvotes: 0
Reputation: 390
The issue comes from newarr[x].push(arr[z+x]);
.
Each time the second loop runs, it adds 1 letter to the first array inside newarr
and 1 letter to the second array inside newarr
.
This is because x
inside the loop (in the case of size
= 2), starts as 0 (the first array) and then becomes 1 (the second array).
To fix this problem:
newarr[x].push(arr[z+x]);
should be changed to newarr[z/size].push(arr[z+x]);
Upvotes: 0
Reputation: 191976
Run over all the items in the array, and whenever the index % size is 0, add another sub array, then push the item to the last sub array.
function chunkArrayInGroups(arr, size) {
var chunks = [];
for(var i = 0; i < arr.length; i++) {
if(i % size === 0) {
chunks.push([]);
}
chunks[chunks.length - 1].push(arr[i]);
}
return chunks;
}
console.log('Size 2', JSON.stringify(chunkArrayInGroups(['a', 'b', 'c', 'd'], 2)));
console.log('Size 3', JSON.stringify(chunkArrayInGroups(['a', 'b', 'c', 'd'], 3)));
console.log('Size 4', JSON.stringify(chunkArrayInGroups(['a', 'b', 'c', 'd'], 4)));
console.log('Size 6', JSON.stringify(chunkArrayInGroups(['a', 'b', 'c', 'd'], 6)));
Upvotes: 2
Reputation: 73241
You could use the Array.slice method together with the loop to chunk an array:
function chunkArrayInGroups(arr, size) {
let i,j,res = [];
for (i=0,j=arr.length; i<j; i+=size) {
res.push(arr.slice(i,i+size));
}
return res;
}
console.log(chunkArrayInGroups(["a", "b", "c", "d"], 2));
Upvotes: 0