This question already has an answer here:
I need to shuffle multiple arrays using the same function so that it randomizes the words up in each sentence.
Using HTML i then need a button that starts the shuffle, with the outputted sentences with line break between each for example:
var array1 = ["The, "Man", "and", "his", "dog"];
var array2 = ["went", "for", "a", "walk", "outside"];
On click of a button "shuffle" im trying to get the output to display on seperate lines like this:
Man and dog his the
for a outside walk went
Thanks
You should use map
and sort
methods.
First of all, you can generate a random number for every item in the array, using Math.random
method. Next step is to sort array by this generated
number.
Last step is to create the sentence with the items of the array, using join
method.
var array1 = ["The", "Man", "and", "his", "dog"];
console.log(array1.map(function(n){
return [Math.random(), n];
}).sort().map(function(item){
return item[1] ;
}).join(' '));
This should do it for you....
["The", "Man", "and", "his", "dog"]
.map(w => { return { seq: Math.random(), word: w } })
.sort((a,b) => a.seq<b.seq?-1:1)
.map(w => w.word)
来源:https://stackoverflow.com/questions/43293454/shuffling-multiple-arrays-javascript