Skip to content Skip to sidebar Skip to footer

How To Shuffle Numbers With Textarea In Javascript

If I put numbers into a textarea like so: 418484 418485 418486 I want them to get shuffled, and I want an output like this: 418485 418484 418486 I don't want the values changed -

Solution 1:

I found this great shuffle function from this answer:

functionshuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  returnarray;
}

From there, you can simply get the value of the <textarea>'s input, and split it based on linebreaks:

var numbers = document.getElementById("numberInput").value.split("\n");

Or if you prefer spaces:

var numbers = document.getElementById("numberInput").value.split(" ");

Then, just pass it into the function:

var shuffledNumbers = shuffle(numbers);

And show them on the page by iterating over them and writing them to the document:

shuffledNumbers.forEach(function(currentNumber) {
    document.write(currentNumber + "<br />");
})

And there you go!

EDIT:

If you want to display the shuffled numbers in another <textarea> instead:

var output = document.getElementById("output");
shuffledNumbers.forEach(function(currentNumber) {
    output.innerHTML += currentNumber + "\n";
})

Post a Comment for "How To Shuffle Numbers With Textarea In Javascript"