javascript – Convert comma-separated string to multidimensional array


I have a string like that…

var listAdd = "1789, 3, 8 , 1788, 3, 8, 1790, 3, 9"

How do I convert to an array like below?

[1789,3,8], [1788,3,8], [1790,3,9]

The code I'm trying isn't working:

var ArrayAdd = new Array();

for (i = 0; i < listAdd.length; i++) {
                s = "";
                s = String(listAdd[i]);


There are several errors there and you can't even start talking about what. There are some ways to solve this, I preferred it this way, although perhaps not the most efficient (but in general people usually propose, and I know they will post even worse here at this point), but I would need to test because without using split() it can give a gain on the one hand and a loss on the other.

Need to break the text into parts according to the comma. Then group 3 by 3 assembling a new array with each new group, if you understand.

I did inferring criteria by the expected response that was posted, there is no such thing as "no more criteria", if they were ambiguous it might not give the real result that it should give because the AP might have been wrong in something putting the problem. Simple and performance:

 let texto = "1789, 3, 8 , 1788, 3, 8, 1790, 3, 9"; let array = new Array(); let quebrado = texto.split(","); for (let i = 0; i < quebrado.length; i+= 3) array.push([parseInt(quebrado[i]), parseInt(quebrado[i + 1]), parseInt(quebrado[i + 2])]); console.log(array);

I put it on GitHub for future reference .

Scroll to Top