0

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.

6 Answers 6

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer! I would go still one step further, and create a reusable function from it. const toWordArray = words => words.split(' ').map(word => word.split('')).
1

Here is what I would do:

1) Split the words by spaces ''

2) Use the spread syntax to expand each word within the above array.

const word = "abc def";

const res = word.split(' ').map(element => [...element]);
console.log(res)

Comments

0

Split the words by space, and then map and split each word:

const words = "abc def";

const result = words.split(' ')
  .map(w => w.split(''));

console.log(result);

Comments

0

I think, This code will help you!

var data = "this is test data";
var arrayData = data.split(' ').map(i=> i.split(''));

console.log(arrayData);

Comments

0

First split the text to words using the space,

Then after getting each word, use the empty string to split by letter

This should work

 let text = "abc def";
 let arrayFinal = [];

 for(let word of text.split(' ')) {
    let letterArray = [];
    for(let letter of word.split('')) {
      letterArray.push(letter);
     }

    arrayFinal.push(letterArray);
  }

refere this

Comments

0

no need to perform nested loop manually, just use split and map to get the result

var word = "abc def";
var wordArray = word.split(" ").map(w => w.split(''));

Comments

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.