I am hoping to place the letters of a string found in an array into subarrays using JavaScript.
For example:
var word = "abc def";
var wordArray = [];
var firstArray = randomWord.split(" ");
for (var l = 0, len = firstArray.length; l < len; l++) {
for (var m = 0, len2 = firstArray[l].length; m < len2; m++) {
console.log(firstArray[l][m]);
WordArray.push(firstArray[l][m]);
WordArray = randomWordArray.filter(function(str) {
return /\S/.test(str);
});
};
};
console.log("word", word);
console.log("wordArray", wordArray);
Currently, I get is ...
wordArray = ["a", "b", "c", "d", "e", "f"];
What I am hoping for is ...
wordArray = [["a", "b", "c"],["d", "e", "f"]];
I suppose the real questions is is this possible?
Thank you, in advance, for any and all suggestions.
You basically want to solve two problems. First, you want to create a separate array for each word (detect word boundaries). Next, you want to split each word into its component letters.
Doing this without any "modern" JavaScript magic (map, reduce, etc) would look something like this:
var word = "abc def";
// Step 1.
var wordArray = word.split(" ");
console.log(wordArray); // ["abc", "def"]
// Step 2.
for (var i = 0; i < wordArray.length; i++)
{
wordArray[i] = wordArray[i].split("");
}
console.log(wordArray); // [["a", "b", "c"], ["d", "e", "f"]]
This second step can be written in a slightly more compact form by realizing that this is what's known as a mapping problem. You want to take every element of the array and convert it from one form (a string) to another (an array of letters). For this, JavaScript provides the map
method:
var squares = [1, 2, 3].map(function(x) { return x * x; });
console.log(squares); // [1, 4, 9]
So we can re-write step 2 using this method like so:
wordArray = wordArray.map(function(word) { return word.split(""); });
Finally, we can simplify further using an arrow function. Arrow functions basically are short-hand for the following:
x => x + 1;
// Is equivalent to:
(function(x) {
return x + 1;
}).bind(this);
Ignore the .bind()
bit for now (it's unimportant for your problem) and we can write step 2 as:
wordArray = wordArray.map(word => word.split(""));
Combining these two improvements we get:
var word = "abc def";
// Step 1.
var wordArray = word.split(" ");
// Step 2.
wordArray = wordArray.map(word => word.split(""));
We can shrink this slightly more by passing the result of word.split(" ")
directly to step 2 without storing it into an intermediate variable:
var word = "abc def";
// Step 1 and 2.
var wordArray = word.split(" ").map(word => word.split(""));
And there you have it. The "modern" answer, created from the basics.