user1620572
user1620572

Reputation: 1

Pushing every value from an Array to multiple sub-arrays

i would like given an array in javascript and a number variable to create new arrays from the number and then push every member of the "big" array to the sub-arrays. The first value from the array goes to the 1st sub-array the second goes to the 2nd sub-array, the 3rd to 3rd etc.Here is how i do it with 2 arrays:

r1=new Array();  
r2=new Array(); 

for(var i=0; i<array.length; i++){
  if(i%2 == 0){
    r1.push(array[i]);
  } 
  else
  {
    r2.push(array[i]);
  }
}

Suppose we have a number variable that is meaning to be the sub arrays , we would then have to do

for(var j=0;j<number;j++){
  r[j]=[];
}

What is the best solution for this?Maybe array.map could help?Thanks.

Upvotes: 0

Views: 303

Answers (1)

jfriend00
jfriend00

Reputation: 707546

Here's a general purpose solution for splitting among N arrays. It returns an array of the resulting arrays.

function splitArray(src, num) {
    var result = [], i;
    // initalize output arrays
    for (i = 0; i < num; i++) {
        result.push([]);
    }
    // split results among the various output arrays
    for (i = 0; i < src.length; i++) {
        result[i % num].push(src[i]);
    }
    return(result);
}

Upvotes: 1

Related Questions