Home > Net >  How to push Strings nested in double for loop into Array
How to push Strings nested in double for loop into Array

Time:03-30

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"]

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)
  }
  
}
  
  

CodePudding user response:

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);

CodePudding user response:

Your approach to create an empty array is right. However, you have a scoping issue here: Variables defined using let are only valid in the current scope, which means the block surrounded by curly braces {}. Therefore, your let empty will get redefined on each iteration of your for loop, causing your first word to use another "bucket" for the variable than the second one and so one.

You can define the empty outside of the loop instead, to persist it throughout different iterations:

let thisString = "I like bacon";
letOfficialSentence = thisString.split(" ")
let empty = []; //> Define it outside the loop!

//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

for (let i = 0; i < letOfficialSentence.length; i  ) {
  let thisFirstWord = letOfficialSentence[i];
  let thisFirstLetter = letOfficialSentence[i][0];
  let thisSubString = thisFirstWord.substring(1);

  let newerWords = thisFirstLetter   thisSubString.shuffle()

  empty.push(newerWords)
  console.log(empty)
}

Similarly, you can define the shuffler outside of the loop as well, since it does not depend on any loop-related data, which will make your loop more readable.

CodePudding user response:

Try this:

String.prototype.shuffle = function() {
  const a = this.split(''),
    n = a.length;

  for (let l = n - 1; l > 0; --l) {
    const j = Math.floor(Math.random() * (l   1));

    [a[l], a[j]] = [a[j], a[l]];
  }

  return a.join('');
}

const scrambleWord = () => {

  const thisString = "I like bacon";
  const officialSentence = thisString.split(' ');
  const needArray = [];

  for (let i = 0; i < officialSentence.length;   i) {
    const thisFirstWord = officialSentence[i];
    const thisFirstLetter = thisFirstWord[0];
    const thisSubString = thisFirstWord.substring(1);

    needArray.push(thisFirstLetter   thisSubString.shuffle());
  }

  return needArray;
}

console.log(scrambleWord());

CodePudding user response:

There is a lot you can simplify in your code. The following function scrambles the sentence passed as an argument:

const scramble = sentence =>
 sentence.split(" ").map(w=>{
  const a=w.split("");
  for (let l = a.length - 1; l > 1; --l) {
   const j = 1 Math.floor(Math.random() * l);
   [a[l], a[j]] = [a[j], a[l]];
  }
  return a.join("");
 });
 
["some silly sentence","And now for something completely different"].forEach(s=>console.log(scramble(s)));

  • Related