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 ]];
});
2
  • 3
    map when given an array as a return flattens it into the new array, you probably just want to do it yourself. Commented May 4, 2012 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). Commented May 4, 2012 at 21:44

5 Answers 5

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 ]]];
});
Sign up to request clarification or add additional context in comments.

3 Comments

+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.
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.
I have rewritten this in standard javascript without jQuery, here: stackoverflow.com/a/10456644/711085
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));
}

Comments

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

Comments

3

Another example...

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

2 Comments

Just realized this is similar to Jonathan M's solution
Nope, you're using splice() and I'm using slice(). Nice job.
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.

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.