8

Possible Duplicate:
Split array into chunks

I am trying to convert an array of values into a new array of paired values.

For example i need to convert:

var arr = [1,2,3,4,5,6,7,8];

into:

arr = [[1,2], [3,4], [5,6], [7,8]];

I tried using jQuery's .map() method like so but this did not work for me:

arr= $.map(arr, function(n, i){
return [n + ',' + n[ i + 1 ]];
});
Community
  • 1
  • 1
RyanP13
  • 7,413
  • 27
  • 96
  • 166
  • 3
    `map` when given an array as a return flattens it into the new array, you probably just want to do it yourself. – Andrew May 04 '12 at 21:20
  • Also `[...].map` is a built-in function in javascript (ECMAScript 5th edition, supported by all modern browsers, unless you count the people who still haven't clicked the "upgrade to IE9" button that Microsoft shoves infront of you). – ninjagecko May 04 '12 at 21:44

5 Answers5

10

If you insist on using map, you could do it like this:

arr= $.map(arr, function(n, i){
    if (i%2 === 0) return [[n, arr[ i + 1 ]]];
});
McGarnagle
  • 101,349
  • 31
  • 229
  • 260
  • +1 this is nice. P.s: use always `===` to compare with `0`. And the use of `{}` (although not needed) is a nice way to write clean code. – Roko C. Buljan May 04 '12 at 21:32
  • 1
    Using modulus is a nice clean way to do this, but I do admit that the for loops seems more appropriate for this kind of thing, even though the OP mentioned map(). Still +1. – adeneo May 04 '12 at 21:34
  • 1
    I have rewritten this in standard javascript without jQuery, here: http://stackoverflow.com/a/10456644/711085 – ninjagecko May 04 '12 at 21:58
7

If you don't want to use a hammer on a thumbtack:

var arr = [1,2,3,4,5,6,7,8];

var newarr = new Array();

for (var i=0; i<arr.length; i=i+2) {
    newarr.push(arr.slice(i,i+2));
}
Jonathan M
  • 17,145
  • 9
  • 58
  • 91
3

You don't want map, you want reduce.

Here is something that should work:

var endArr = [],
    arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ],
    i = 0;

arr.reduce( function( prev, curr, index ) {
    if ( index % 2 === 0 ) {
        endArr[ i ] = [ prev, curr ];
    }
    i++;
} );

And just something else I thought about:

var endArr = [],
    arr = [ 1, 2, 3, 4, 5, 6, 7, 8 ];

while ( arr.length ) {
    endArr.push( arr.splice( 0, 2 ) );
}

Edit: Arf, it's the same solution as Chris Gutierrez.

Community
  • 1
  • 1
Florian Margaine
  • 58,730
  • 15
  • 91
  • 116
3

don't use jquery for every problem:

var arr = [1, 2, 3, 4, 5, 6, 7, 8];
var narr = [];
for (i = 0; i < arr.length; i = i + 2) {
    narr[i / 2] = [arr[i], arr[i + 1]];
}

but this only works if you have an even count of arr

Neysor
  • 3,893
  • 11
  • 34
  • 66
3

Another example...

var arr = [1 , 2, 3, 4, 5, 6, 7, 8]
var final = []
while(arr.length) {
    final.push(arr.splice(0, 2))
}
Chris Gutierrez
  • 4,750
  • 19
  • 18