Reputation: 469
How do I remove the last item of an array inside of an array. In this case, I want to remove the null at the end of my array inside of an array. Here's my code
function chunkArrayInGroups(arr, size) {
// Break it up.
var arrWithSubArr = [];
for(var i = 0; i < arr.length / size; i++){
arrWithSubArr.push([]);
}
var index = 0;
var whichSubArr = 0;
for(whichSubArr = 0; whichSubArr < arr.length / size; whichSubArr++){
for(i = 0; i < size; index++){
arrWithSubArr[whichSubArr].push(arr[index]);
i++;
}
}
return arrWithSubArr;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4);
Upvotes: 0
Views: 99
Reputation: 64
I believe your ultimate goal is to split the original array into a number of arrays each equal to or less than the size specified (in the case that the last sub array will not be equal to size
). Rather than removing undefined values that get added in the loop it would be easier to prevent them from getting inserted at all.
function chunkArrayInGroups(arr, size) {
// Break it up.
var arrWithSubArr = [];
var whichSubArr = 0;
// Using Math.ceil returns the smallest integer greater than or equal to the number
// In this case your minimum number of sub arrays needed to contain all the items of the original array
var numOfSubArrs = Math.ceil(arr.length/size);
// create the empty sub arrays
for(var i = 0; i < numOfSubArrs; i++){
arrWithSubArr.push([]);
}
for (var i =0; i < arr.length; i++) {
arrWithSubArr[whichSubArr].push(arr[i]);
// starting with the inital sub array at position 0
// increment to the next sub array once the current one is equal to the specified size
if (arrWithSubArr[whichSubArr].length == size){
whichSubArr++;
}
}
return arrWithSubArr;
}
chunkArrayInGroups([0, 1, 2, 3, 4, 5], 4);
Upvotes: 1
Reputation: 81
To remove the last item in the array and alter the original array. I would use
arr.pop();
Upvotes: 0