1

I am rather new to JS and I was working on a problem that asked to split an array (first argument) into groups the length of size (second argument) and returns them as a multidimensional array. I got the problem to work right for all test cases but it suggested using the array `push()` method. I tried it multiple times and couldn't ever get it to work right. I think I was getting messed up with arrays being by reference. I eventually declared a new Array for each element. I went with a more classic deep copy each element at a time. I Didn't go back and try the `push()` method again. There has to be a more efficient way to do this. I want to write good code. Would love to see better versions please. Thanks!

function chunk(arr, size) {

    var group = 0;
    var counter = 0;
    var even = false;
    var odd = false;

    if (arr.length % size === 0) {
        group = arr.length / size;
        even = true;
    } else {
        group = Math.ceil(arr.length / size);
        odd = true;
    }

    var newArr = new Array(group);

    for (var i = 0; i < group; i++) {
        newArr[i] = new Array(size);
    }

    for (i = 0; i < group; i++) {
        for (var j = 0; j < size && counter < arr.length; j++) {
            newArr[i][j] = arr[counter++];
        }

    }

    return newArr;
}

chunk(['a', 'b', 'c', 'd'], 2);
  • possible duplicate of [How to convert simple array into two-dimensional array(matrix) in javascript (or jquery)](http://stackoverflow.com/questions/4492385/how-to-convert-simple-array-into-two-dimensional-arraymatrix-in-javascript-or) – jwueller Aug 07 '15 at 19:15

2 Answers2

4

Using Array.prototype.slice, the function can be written in a shorter way:

function chunk(array, size) {
  var result = []
  for (var i=0;i<array.length;i+=size)
    result.push( array.slice(i,i+size) )
  return result
  }
rplantiko
  • 2,698
  • 1
  • 22
  • 21
-1

You can try the slice method from the Array object. Here's an idea on how to use it.

var arr = [1, 2, 3, 4, 5, 6];
var newArr = [];
newArr.push(arr.slice(0, arr.length / 2));
newArr.push(arr.length / 2, arr.length);

This is just an shallow implementation but you can use the same concept inside a better written function.

Here's an example function:

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];

function toChunks(arr, size) {
  var i = 0,
      chunks = [];

  for (; i < arr.length; i += size) {
      chunks.push(arr.slice(i, i + size););
  }

  return chunks;
}

toChunks(arr, 2);
David Gomez
  • 2,762
  • 2
  • 18
  • 28