Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to push Strings nested in double for loop into Array

Trying to shuffle words in a sentence and put them back together in an array. Shuffling is no biggie, but the putting back together is the issue.

(I can only scramble everything after the first letter hence why things are a bit more complex.)

Current output is ["I"] ["leik"] ["bnoca"]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Desired output ["I", "leik", "bnoca"]

Tried creating an empty array called "empty". Then I want to push the items into the array, But having issues because of for loop? I think?

Here is the codepen from the image. Couldnt upload the code on here for some reason?
https: //codepen.io/halfrussian/pen/gOoRKMj

const scrambleWord = () => {
  
  let thisString = "I like bacon";
  letOfficialSentence = thisString.split(" ")
  
  for(let i = 0; i < letOfficialSentence.length; i++){
    let thisFirstWord = letOfficialSentence[i];
    let thisFirstLetter = letOfficialSentence[i][0];
    let thisSubString = thisFirstWord.substring(1)
    
    //shuffler
    //see https://stackoverflow.com/questions/3943772/how-do-i-shuffle-the-characters-in-a-string-in-javascript
    
      String.prototype.shuffle = function () {
        var a = this.split(""),
            n = a.length;
        for(var l = n - 1; l > 0; l--) {
            var j = Math.floor(Math.random() * (l + 1));
            var tmp = a[l];
            a[l] = a[j];
            a[j] = tmp;
        }
        return a.join("");
    }
    
    //end of shuffler
    
    let newerWords = thisFirstLetter + thisSubString.shuffle()
    let empty = [];
    empty.push(newerWords)
    console.log(empty)
  }
  
}
  
  

>Solution :

You are creating the empty array and adding each word to it separately inside of the for loop.

Move the definition of empty to before your for loop:

  let empty = []; 

And then place console.log after your loop:

  console.log(empty);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading