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] ]?
1 Answer
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>');