0

I'm trying to create new array of array from one array,

How to make

var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];

become

var array = [['1', '2'], ['3', '4'], ['5', '6'], ['7', '8'], ['9', '10']];

  • Welcome to StackOverflow! Please take the [tour](http://stackoverflow.com/tour) and read [How do I ask a good question?](http://stackoverflow.com/help/how-to-ask). Then come back and edit your question accordingly. – Jan Mar 15 '17 at 08:03

2 Answers2

1

Use a simple loop with Array#splice method to update the same array.

var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
  size = 2;

// iterate upto the length(which is dynamic)
for (var i = 0; i < array.length; i++)
  // remove the 2 elements and insert as an array element
  // at the same index
  array.splice(i, 0, array.splice(i, size));

console.log(array);

In case you want to generate a new array then use Array#slice method.

var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
  size = 2,
  res = [];

// iterate over the array where increment index by the size
for (var i = 0; i < array.length; i += size)
  // push the subarray
  res.push(array.slice(i, i + size));

console.log(res);

An ES6 alternative with Array.from method:

var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
  size = 2;

var res = Array.from({
  // create an array of size based on the chunk size
  length: Math.ceil(array.length / size)
  // iterate and generate element by the index
}, (_, i) => array.slice(i * size, i * size + size))

console.log(res);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
1

Try the following:

var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var newArray = [];
var i,j,chunk = 2;
for (i=0,j=array.length; i<j; i+=chunk) {
    newArray.push(array.slice(i,i+chunk));
}
console.log(newArray);
Mamun
  • 66,969
  • 9
  • 47
  • 59