I am working through a javascript problem that asks me to:
Write a function that splits an array (first argument) into groups the length of size (second argument) an
So many Ways...
function chunkArrayInGroups(arr, size) {
var value = [];
for(var i =0; i<arr.length; i += size){
value.push(arr.slice(i, size+i));
}
return value;
}
chunkArrayInGroups(["a", "b", "c", "d"], 2);
The problem is that you are both advancing i
by size
at each iteration and removing size
elements from position i
. This causes you to skip processing every other chunk. Also, your continuation condition should be i < arr.length-size
; as it is, you would need to test for an empty temp
before pushing it after the loop exits. Try rewriting your loop as:
for (i = 0; i < arr.length-size;){
newArray.push(arr.slice(i,i+size));
temp.splice(i,size);
}
Since i
is always at 0, the loop can be simplified to:
while (arr.length > size) {
newArray.push(arr.slice(0,size));
temp.splice(0,size);
}
function chunk(arr, size) {
var newArr = []; // New empty array
while (arr.length > 0) { // Loop thru the array items
newArr.push(arr.splice(0, size)); // Removes first 2 items then add it to new array
}
return newArr; // New 2D array
}
I tried using these lines of codes in console and it worked perfectly fine.
function chunkArrayInGroups(arr, size) {
var temp = [];
var result = [];
for (var a = 0; a < arr.length; a++) {
if (a % size !== size - 1)
temp.push(arr[a]);
else {
temp.push(arr[a]);
result.push(temp);
temp = [];
}
}
if (temp.length !== 0)
result.push(temp);
return result;
}
function chunkArrayInGroups(arr, size) {
var result = [],
iterations = Math.ceil(arr.length/size);
for (var i =0; i<iterations;i++){
var sub = arr.splice(0, size);
result.push(sub);
}
return result;
}
function chunk(arr, size) {
var newArr = [];
// x is less than or equals arr.length.
for(var x = 0; x <= arr.length; x++){
newArr.push(arr.splice(0, size));
}
if (arr.length){
newArr.push(arr);
}
return newArr;
}
chunk(['a', 'b', 'c', 'd'], 2);