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] ]?
            Asked
            
        
        
            Active
            
        
            Viewed 1,461 times
        
    2
            
            
         
    
    
        Meow
        
- 1,610
- 1
- 14
- 18
- 
                    https://jsfiddle.net/uxqwzvcj/1/ – osmanraifgunes May 17 '16 at 08:20
1 Answers
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