Have I created an anti-pattern here? Is there anything that would be more logical, and can you explain why?
your code contains a few improvable parts
function chunk(arr, size) {
//newWhatever, myWhatever, ... look for a better naming like `out` or `result`
//or in this case `chunks` would describe the content of the variable
var newArr = [];
//you initialize `i` without the var-keyword, therefore you populate/pollute the global namespace
//and instead of calculating i+=0, you can leave this part empty:
//for(var i=0; i<arr.length; ){
for (i=0; i<arr.length; i+=0) {
var sliced = arr.slice(i, size);
newArr.push(sliced);
//splicing (with P) is often a thing that should be avoided,
//- it is destructive (it destroys the input-array)
//- it is slow, cause the engine has to allocate new memory
// and copy the remaining elements over to this memory,
// and garbage-collect the old memory
arr.splice(0, size);
}
return newArr;
}
a better solution would be:
function chunk(arr, size) {
for(var chunks=[], i=0; i<arr.length; i+=size)
chunks.push(arr.slice(i, size));
return chunks;
}
assuming that the inputs are right.
For completenes, you should add some validation of the inputs. That arr is in place, can be sliced, and has a length-property.
And that size is an integer > 0 otherwise the code may create strange results.
function chunk(arr, size) {
//checks if arr is not empty and arr.slice is not empty
//and casts the length-property to int
//if anything "fails" len = 0;
var len = (arr && arr.slice && arr.length)|0;
//check if size is > 1 and is an integer
if(size !== Math.floor(size) || size < 1)
throw new Error("invalid chunl-size: "+size);
for(var chunks=[], i=0; i<len; i+=size)
chunks.push(arr.slice(i, size));
return chunks;
}
Array.slice(). Also if objective of this question is to seek improvements, you should try CodeReviews instead