Please check out my idea to add a function to split an array into chunks:
It looks like this is successfully implemented as library code. What benefit do you see to moving it into Array.prototype?
I suspect mainly for better performance but it is also a common need for people. (I'd put it somewhere between .reduceRight()
and .lastIndexOf()
in terms of utility and use case.) I do want to point out that you could theoretically implement Array.prototype.map
and friends in userland, too (and V8 did this for quite a while), so although it is reason to question, it's not reason to immediately dismiss.
I had a similar idea and I'm using a IMO slightly easier to read syntax:
Array.prototype.chunk = function(size) {
return this.reduce((chunks, element, index) => {
if (index % size === 0) chunks.push([]);
chunks[chunks.length - 1].push(element);
return chunks;
}, []);
}
another varation since Array.push returns the new length of the array:
Array.prototype.chunk = function(size) {
return this.reduce((chunks, element, index) => {
chunks[(index % size === 0 ? chunks.push([]) : chunks.length) - 1].push(element);
return chunks;
}, []);
}
I do also believe that this extension can come in handy in various situations.
@faxemaxee Yeah I did something similar yesterday while building a Web Application. I had this array that'll have lots of items in it, and I want to chunk them in tens. [ 50 items ] --> [ [10], [10], [10], [10], [10] ] so that I'll assign each ten to different objects as their share of the items.