bikky barnwal bikky barnwal - 1 month ago 5
Javascript Question

Concat sequential 2 elements of an array as an array in new array

Suppose if we have an array [1,2,3,4,5,6], i want to get a new array [[1,2],[3,4],[5,6]]. I don't want to use for loop.I want to solve it using map-reduce or using best practice but I am not getting how to use map-reduce. please help.

Answer

You could use the remainder operator % for checking. If zero, push to the last inserted array otherwise to result with a new array.

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

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }