2

How do I write a javascript function that takes an array as its input [0, 1, 2, 3, 4, 5, 6, 7, 8] and returns [ [0, 1], [2, 3], [4, 5], [6, 7], [8] ]?

Meow
  • 1,610
  • 1
  • 14
  • 18

1 Answers1

3

You could use Array#reduce and the index for grouping the parts.

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8],
    result = array.reduce(function (r, a, i) {
        if (i % 2) {
            r[r.length - 1].push(a);
        } else {
            r.push([a]);
        }
        return r;
    }, []);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392