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]]
You can use js reduce
There's no pre-baked function to do that, but here's a simple solution:
Here is a short and more generic solution:
Where arr is your array and n is no of pairs
Yet another that's a bit of a mish-mash of the already-posted answers. Adding it because having read the answers I still felt things could be a little easier to read:
Here's another solution using lodash helpers:
There is now the flexible
Array#flatMap(value, index, array)
:And the possibly more efficient, but goofy looking
Array.from(source, mapfn?)
: