I want to split an array into pairs of arrays
so var arr=[2,3,4,5,6,4,3,5,5]
would be newarr =[[2,3],[4,5],[6,4],[3,5],[5]]
I want to split an array into pairs of arrays
so var arr=[2,3,4,5,6,4,3,5,5]
would be newarr =[[2,3],[4,5],[6,4],[3,5],[5]]
A slightly different approach than using a
for
loop for comparison. To avoid modifying the original arrayslice
makes a shallow copy since JS passes objects by reference.const items = [1,2,3,4,5];
const createBucket = (bucketItems, bucketSize) => buckets => { return bucketItems.length === 0 ? buckets : [...buckets, bucketItems.splice(0, bucketSize)]; };
const bucketWithItems = items.reduce(createBucket([...items], 4), []);
I would use lodash for situations like this.
Here is a solution using
_.reduce
:Here's a good generic solution:
For your case, you can call it like this:
The
inplace
argument determines whether the operation is done in-place or not.Here's a demo below:
It's possible to group an array into pairs/chunks in one line without libraries:
Lodash has a method for this: https://lodash.com/docs/4.17.10#chunk
_.chunk([2,3,4,5,6,4,3,5,5], 2); // => [[2,3],[4,5],[6,4],[3,5],[5]]