How to split a string into array, randomly in jquery

19,962

Solution 1

Native sort() function can get a function as parameter to let you decide how to sort your array.

So you can give it a function to generate random results.

var str = 'one, two, three';
var substr = str.split(', ');

substr.sort(function () {
    return( parseInt( Math.random()*10 ) %2 );
});

Solution 2

I've mostly got the same answer as keune, just some style differences :)

var random_results = 'one, two, three'.
                        split(/\s*,\s*/).
                        sort(function(){
                            return (-1 + Math.floor((Math.random() * 3))) 
                        })
  • I changed your explicit ', ' split to a regex. If you intend to only match on that specific substring, it's fine, but if you're dealing with user input it's handy to write your split such that you handle the presence of spaces before or after commas and have them stripped out for you by the split function.
  • keune and I both compute return values differently for our sort() function. Both provide random results; so long as you return a random integer value that may be negative or positive, you can get your shuffled array.

Also, as a minor style note, this has nothing to do with JQuery. This is pure JavaScript.

Share:
19,962
aurel
Author by

aurel

I love JavaScript, reading books, drinking coffee and taking notes.

Updated on June 14, 2022

Comments

  • aurel
    aurel almost 2 years

    I have this code:

    var str = 'one, two, three';
    var substr = str.split(', ');
    

    That will create the array as we'd expect. But is there a way to split the words, shuffle them and then insert them into the substr array? Thanks