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