Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you split an array into array pairs in JavaScript?

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] ] 
like image 460
Tormod Smith Avatar asked Jul 11 '15 00:07

Tormod Smith


People also ask

How do you split an array into two parts?

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.


2 Answers

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; }, []); 
like image 75
Vbyec Avatar answered Sep 19 '22 13:09

Vbyec


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]]

like image 33
vinniecent Avatar answered Sep 18 '22 13:09

vinniecent