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.
-
1What error? Please include all pertinent information in your questionJames Thorpe– James Thorpe2015年01月05日 23:00:20 +00:00Commented Jan 5, 2015 at 23:00
-
2Stack offers runnable snippets now, you should use that instead of that weird fiddle like websiteSterling Archer– Sterling Archer2015年01月05日 23:01:26 +00:00Commented Jan 5, 2015 at 23:01
-
Also consider cleaning up your code samples before posting them; we don't need those random commented-out bits at the bottom.AstroCB– AstroCB2015年01月05日 23:06:00 +00:00Commented Jan 5, 2015 at 23:06
1 Answer 1
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);
1 Comment
push command just "pushes" another value onto the end of an array. You can also pop the value off again. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…