Ugur
Ugur

Reputation: 312

Creating array of arrays with JavaScript

I have the following code, which when run gives error: TypeError: Cannot read property 'split' of undefined
Here you can run it.

var myData = "some1,some2,some3\nsome4,some5,some6\nsome7,some8,some9";
var arrayed = myData.split('\n');
var columns = arrayed.length;
var urlArray = new Array(columns);
console.log(arrayed);
var newarrayed = arrayed.split(',');
console.log(newarrayed);

I have myData array, I want to convert it to an array of arrays, splitting first at \n to seperate arrays, and second at , to create the items inside the arrays. so this list would be like:

[[data1, data2, data3], [data4, data5, data6], [data7, data8, data9]]

console.log(arrayed); does something similar, but when I try to access it using arrayed[0][0], it gives me just the first letter.

Upvotes: 0

Views: 44

Answers (1)

Joseph Marikle
Joseph Marikle

Reputation: 78520

You're not splitting the strings correctly. You try to split them twice, but the second time fails because you are calling split on an array, not a string. Try looping over them instead.

var myData = "some1,some2,some3\nsome4,some5,some6\nsome7,some8,some9";
var arrayed = myData.split('\n');
var columns = arrayed.length;
var urlArray = new Array(columns);
console.log(arrayed);
var newarrayed = [];
for (var i in arrayed) {
    newarrayed.push(arrayed[i].split(','));
}
console.log(newarrayed);

Upvotes: 4

Related Questions