Arun Kumar A Arun Kumar A - 5 months ago 6
Javascript Question

Storing each character of each string of an array into a new 2d array

I intend to split a string into a 2d array in javascript in the format of [[],[],[]...] with each word corresponding to each index of the outer array and each letter of each word corresponding to indices of inner arrays and log the contents of the arrays into the console. The code is below:

function titleCase(str) {
var str_to_words=str.split(" ");
var str_to_letters;
for(var i=0;i<str_to_words.length;i++)
{
str_to_letters[i]=str_to_words[i].split();

}
return str_to_letters;
}

console.log(titleCase("I'm a little tea pot"));


But I get an error : "script.js:6 Uncaught TypeError: Cannot set property '0' of undefined" Can anyone please help? I am new to javascript syntax.

Answer

The important thing is .split(''); Split without nothing returns string but split supplied with empty string returns array with characters.

So

'abc'.split() => 'abc'

but

'abc'.split('') => ['a','b','c']

function titleCase(str) {
    var str_to_words=str.split(" ");
    var str_to_letters = [];
    var res = [];
    for(var i=0;i<str_to_words.length;i++)
    {
        str_to_letters[i]=str_to_words[i].split('');

    }
    return str_to_letters;
}

console.log(titleCase("I'm a little tea pot"));

Comments