0

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.

3
  • 1
    What error? Please include all pertinent information in your question Commented Jan 5, 2015 at 23:00
  • 2
    Stack offers runnable snippets now, you should use that instead of that weird fiddle like website Commented 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. Commented Jan 5, 2015 at 23:06

1 Answer 1

4

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

1 Comment

@Ugur You're welcome. Glad I could help. :) The 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/…

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.