I’m trying to write a basic function to “scramble” (rearrange the letters of) a word. My thinking was to:
take the word as an argument
use a loop to assign the string to an array
use another loop to go through the array, randomly picking items from the array and pushing them to another array, and then splicing those items from the original array
repeating that loop until all the items have been spliced (and thus the loop stops)
logging the new “randomized” array to the console
I’m realizing that a while loop might have been a better choice to accomplish this, but to start with, this idea is not working, so I’m wondering why this isn’t functioning:
function rand(word) {
const wordArr = [];
const newArr = [];
for (i = 0; i < word.length; i++) {
wordArr.push(word[i]);
}
for (j = 0; j < wordArr.length; j++) {
let pick = Math.floor(Math.random() * wordArr.length);
newArr.push(wordArr[pick]);
wordArr.splice(pick, 1);
}
console.log(newArr);
}
What you can try is instead of using wordArr.length
for (j = 0; j < wordArr.length; j++)
Use word.length
for (j = 0; j < word.length; j++)
because the problem is that you’re asking for the second loop to grab a not finished array from the first loop because the first loop will run and then the second one will run until the second one is done, then the first one can go again.
there is the result.
@El_Escandalo, I don’t really know how it works, I tried it on a different code and it also works, I don’t understand , maybe its just a built in feature? But still always declare it as a variable.