1

I want to randomly shuffle these two arrays in the same function

var array1 = [1,2,3,4,5];
var array2 = [6,7,8,9,10];

So that it returns each array randomly shuffled such as

4,2,3,5,1
7,9,6,8,10

Also on return I want a line break between the two, please help?

somethinghere
  • 16,311
  • 2
  • 28
  • 42
AB1412
  • 25
  • 1
  • 2
    First off, search 'shuffle array' on stack overflow to find that. Secondly, the output is as simple as something like `document.body.innerHTML = array1.join(',') + '
    ' + arrat2.join(',')`. There you go. Both of these are easily findable on this site with a little googling...
    – somethinghere Apr 07 '17 at 15:10
  • @somethinghere Don't tell OP to do `document.body.innerHTML =` . Nothing in their post suggested they wanted to replace their entire body HTML with that data. – itamar Apr 07 '17 at 15:19
  • @itamar nothing in this post actually suggest _where_ he _wants_ the output _at all_. I use `document.body` to have an example that _can_ at least work and show how simple this can be (I did say _'something like'_, not _'the only way to do this is'_). Anyhow, this wasn't my point. Both of these things are very easily findable on this site. And no, I am not trolling. – somethinghere Apr 07 '17 at 15:20

1 Answers1

1

Added shuffle method to Array.prototype for easy access - returns a modified array keeping the original unchanged.

Array.prototype.shuffle = function() {
  var rIndex, temp,
    input = this.slice(0),
    cnt = this.length;

  while (cnt) {
    rIndex = Math.floor(Math.random() * cnt);
    temp = input[cnt - 1];
    input[cnt - 1] = input[rIndex];
    input[rIndex] = temp;
    cnt--;
  }

  return input;
}

var array1 = [1, 2, 3, 4, 5];
var array2 = [6, 7, 8, 9, 10];

document.getElementById('shuffle-btn').onclick = function(){
  document.getElementById('output').innerHTML = [array1.shuffle(), array2.shuffle()].join('\n');
}
<button id="shuffle-btn">Shuffle</button>
<pre id="output"></pre>
ajai Jothi
  • 2,284
  • 1
  • 8
  • 16