-1

So I'm trying to randomly select an element from a string, copy that element into another array, and then delete the randomly selected element from the original string.

However, I can't seem to get my code to do this properly. I tried slicing and popping the original string but neither technique seems to work, and I don't know why. If anyone could help, I would be very appreciative.

for (var i=0; i < inputword.length; i++)
{
    letter = inputword[Math.floor(Math.random() * inputword.length)];
    anagram[i]=letter;
    inputword.slice(letter,1);
}

$("label").text(anagram);
Calcolat
  • 838
  • 2
  • 11
  • 21
user3394907
  • 131
  • 3
  • 8
  • 1
    If you had just copy/pasted the title of your question into google and clicked the first link, you wouldn't have had to do all of that typing. http://stackoverflow.com/questions/5767325/remove-a-specific-element-from-an-array-in-javascript – Luke Aug 05 '15 at 17:22

3 Answers3

1

The correct way in your code would be

inputword = inputword.slice(letter,1);

Because slice() returns a new Array.

Alternately you can use splice() which modifies the existing array.

Zaphyk
  • 157
  • 2
  • 8
1

Slicing returns a shallow copy of the original array, it does not alter the original array. As Zaphyk states you'd want to assign the return of slice to "inputword" to have the removal persist to your original array.

Be careful with splice because it acts on the original array but returns the removed elements!

Community
  • 1
  • 1
Adam42
  • 11
  • 2
0
for (var i=0; i < inputword.length; i++)
{
  letter = inputword[Math.floor(Math.random() * inputword.length)];
  anagram[i]=letter;

  //You need to reassign your sliced word
  inputword = inputword.slice(letter,1);
}
$("label").text(anagram);
FirebladeDan
  • 1,039
  • 6
  • 14