-1

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

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
AB1412
  • 25
  • 1
  • http://stackoverflow.com/questions/6274339/how-can-i-shuffle-an-array – Mihai Apr 08 '17 at 11:26
  • This is a question and answer site. There is no question here nor is there any mention of problems you are having trying to accomplish your goal. All you have provided is a goal and this is also not a free code writing service – charlietfl Apr 08 '17 at 11:31
  • You've asked the same question (only with different array content) yesterday: [Trying to shuffle multiple arrays in javascript but in the same way?](http://stackoverflow.com/questions/43281492/trying-to-shuffle-multiple-arrays-in-javascript-but-in-the-same-way) – Andreas Apr 08 '17 at 11:43
  • @AB1412, it is working for you ? – Mihai Alexandru-Ionut Apr 08 '17 at 12:34

2 Answers2

2

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(' '));
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

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)
user3094755
  • 1,561
  • 16
  • 20