0

Ok i'v been trying many deferent things to get this to work.

I need a string separated by commas into a 2 dimensional array... like this for example:

string = "a,b,c,d,e,1,2,3,4,5";
array = [['a','1'],['b','2'],['c','3'],['d','4'],['e','5']];

This is the code I have been tweaking.

var temp = list.split(',');
questions = [[''],[''],[''],[''],['']];
five = 0;
one = 0;
for(var i = 0; i < temp.length; i++) {
    if(one == 5){five++; one = 0;}
    one++;
    questions[one][five] = temp[i];
}

btw list = "a,b,c,d,e,1,2,3,4,5".

Thank's in advance!!!

2 Answers 2

1

I'd suggest a slightly different approach, that avoids the (to my mind overly-) complex internals of the for loop:

var string = "a,b,c,d,e,1,2,3,4,5",
    temp = string.split(','),
    midpoint = Math.floor(temp.length/2),
    output = [];

for (var i=0, len=midpoint; i<len; i++){
    output.push([temp[i], temp[midpoint]]);
    midpoint++;
}

console.log(output);

JS Fiddle demo.

Sign up to request clarification or add additional context in comments.

3 Comments

This look's good but i intend to add more to that string by fives(the amount of fives will increase)... But thank's anyway i might use some of this.
So what would the string look like, and what would you want the result to be? (I ask more out of curiosity, and because I'm curious as to the challenge, than any other reason.)
The string could be any size because the program let's you create it. So someone could add as many as they want but it always comes in fives.
1

OK so i fixed it before i asked the question... but i did so much work i'll post it anyway.

This is the code i have now that works:

    var temp = list.split(',');

questions = [[],[],[],[],[]];

for(var i = 0; i < temp.length; i++) {
    questions[i%5][Math.floor(i/5)] = temp[i];
    one++;
}

Thank You Barmar!!!

2 Comments

You don't need 3 variables. questions[Math.floor(i/5)][i%5] = temp[i];
Thank You i started trying to do something like this but i couldn't get it right it works great!

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.