I want to split an array into pairs of arrays.
var arr = [2, 3, 4, 5, 6, 4, 3, 5, 5]
would be
var newarr = [ [2, 3], [4, 5], [6, 4], [3, 5], [5] ]
To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.
You can use js reduce
initialArray.reduce(function(result, value, index, array) { if (index % 2 === 0) result.push(array.slice(index, index + 2)); return result; }, []);
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With