Ad

How To Split A String Into Array, Randomly In Jquery

- 1 answer

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

Ad

Answer

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 );
});
Ad
source: stackoverflow.com
Ad