0

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.

1 Answer 1

1

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

1 Comment

@wvxvw - I fixed the typo on the push. The parens on the return statement is a personal style choice. I use them because it prevents mistakes with multiline or multistatement return values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.