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

1

1 Answer 1

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>');

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.