-2

I want to randomize user input string using sort() function.. but it's not working properly. Can anybody help me solving this problem?

function getAndSetVal() {
  var txt1 = document.getElementById('txt').value;
  document.getElementById('txt2').value = txt1;
}

// get value
function getVal() {
  var txt = document.getElementById('txt').value;
  alert(txt);
  txt1.sort(function() {
    return .5 - Math.random();
  });
}
<input type="text" id="txt" name="txt" onclick="this.value = '' " />
<button onclick="getAndSetVal();">Get Value</button>
<input type="text" id="txt2" name="txt" onclick="this.value = '' " />
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Vicky
  • 5
  • 1
  • 5

2 Answers2

0

String are arrays in some sense but not really, so you have to create an array to use the sort function, try like this:

    function shuffle(){
        document.getElementById('txt2').value = getVal();
    }

    function getVal()
    {
        const txt = document.getElementById('txt').value;
        return txt
            .split(",")
            .map(word => word.trim())
            .sort((a, b) => Math.random() > .5 ? 1 : -1)
            .join(", ");
    }
<input type="text" id="txt" name="txt" value="orange, avocato, banana, fruit" />
<button onclick="shuffle()">Shuffle</button>
<input type="text" id="txt2" name="txt" />

And the sort function pass two parameter and expect return the values 1, -1 or 0.

1 when the first parameter should came first

-1 when the second parameter should came first

0 when doesn't matter the order between both parameters

Kevyn Klava
  • 316
  • 1
  • 7
0

You need to split the word, sort, and re-join.

If the random number i.e. 0 -> 1 falls in:

  • the first third, return -1
  • the last third, return +1
  • the middle, return 0

Edit: Instead of Math.random() (which is predictable), you can implement a seeded random number generator. David Bau's seedrandom library is light-weight and easy to integrate into your JavaScript application.

Just drop the script in your <head> and instantiate a new random number generator with a seed of the current time in milliseconds.

var random = new Math.seedrandom(new Date().getTime());

function shuffle() {
  document.getElementById('txt2').value = randomSort(document.getElementById('txt').value);
}

function randomSort(value) {
  return value.trim().split(/\s*,\s*/).sort((a, b) => {
    return ((p) => {
      return p < (1/3) ? -1 : p > (2/3) ? +1 : 0;
    })(random()); // Instead of Math.random()
  }).join(', ');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/seedrandom/3.0.5/seedrandom.min.js"></script>
<input type="text" id="txt" name="txt" value="Banana, Orange, Apple, Mango" />
<button onclick="shuffle()">Shuffle</button>
<input type="text" id="txt2" name="txt" />
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(function(){return .5-Math.random();}); document.write(fruits); – Vicky Mar 18 '20 at 14:37
  • look at above code how its randomize all strings separately but i just want randomize user input string – Vicky Mar 18 '20 at 14:38
  • @Vicky how are they inputting the values? – Mr. Polywhirl Mar 18 '20 at 14:56
  • Shuffling with `sort()` is [slow](https://jsperf.com/array-shuffle-mine/1) and inefficient (try *shuffling* `abcdefg`-string several times - it returns original string after couple of iterations). There's a much faster and *way more random* [shuffling method](https://stackoverflow.com/a/56749849/11299053). I know, you have taken that from OP, but proceeding this way means encouraging OP to go wrong way. – Yevhen Horbunkov Mar 18 '20 at 15:00
  • ABC, xyz, sunny, funny, pqr ...... like this – Vicky Mar 18 '20 at 15:00
  • @YevgenGorbunkov I addressed the random issue. – Mr. Polywhirl Mar 18 '20 at 16:43
  • @Vicky Just split the words by optional white-space (surrounded) commas, sort with a random number, and join the words back into a string. – Mr. Polywhirl Mar 18 '20 at 16:44
  • thanks for help ... problem solved – Vicky Mar 18 '20 at 16:55
  • @Vicky I just updated my response, since you did not originally say you were splitting on words. – Mr. Polywhirl Mar 18 '20 at 17:03
  • @Mr.Polywhirl : *'...I addressed the random issue'* and it is still slow and now unnecessarily overcomplicated – Yevhen Horbunkov Mar 19 '20 at 07:50