0

I have an array

var array = ["what","is","going","on"];

I know it's possible to access and list these elements with a standard for loop like so:

for (i = 0; i <= array.length; i++) {
  console.log(array[i]);
  }

But I want to know if there's a way to list these elements in a random order. I suspect that I have to use some variation of Math. but I don't have enough experience to decide which to use for sure. Thanks in advance!

Rounin
  • 27,134
  • 9
  • 83
  • 108
mujiha
  • 9
  • 2

4 Answers4

0

You should first shuffle the array and then read one by one. An array method like Array.prototype.shuffle() might come handy.

Array.prototype.shuffle = function(){
  var i = this.length,
      j,
    tmp;
  while (i > 1) {
    j = Math.floor(Math.random()*i--);
    tmp = this[i];
    this[i] = this[j];
    this[j] = tmp;
  }
  return this;
};

var arr = [1,2,3,4,5].shuffle();
for(var i = 0; i < arr.length; i++) console.log(arr[i]);
Redu
  • 25,060
  • 6
  • 56
  • 76
0

Statistically speaking, this will definitely work. It just may take until the heat-death of the universe to complete.

var array = ["What", "am", "I", "doing", "with", "my", "life"];
var processed = [];

function randomAccess() {
  if (processed.length === array.length) {
    console.log('Done!');
    return;
  }
  
  var index = Math.floor(Math.random() * array.length);
  if (processed.indexOf(index) === -1) {
    // Make sure we haven't processed this one before
    console.log('array[' + index + ']:', array[index]);
    processed.push(index);
  }
  // Prevent locking up the browser
  setTimeout(randomAccess, 0);
}
randomAccess();

Please don't use this in production code. Theoretically, it may never complete.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

Yes, you can introduce a second array to log the indices you have randomly returned - in order not to return the same index more than once.

Working example:

var myArray = ['what','is','going','on'];
var returnedIndices = [];

for (i = 0; i < myArray.length; i++) {

    var randomIndex = Math.floor(Math.random() * myArray.length);

    if (returnedIndices.indexOf(randomIndex) !== -1) {
        i--;
        continue;
    }

    else {
        returnedIndices[i] = randomIndex;
        console.log(myArray[randomIndex]);
    }
}
Rounin
  • 27,134
  • 9
  • 83
  • 108
  • 1
    Okay thanks everyone; It seems like a combination of Math.floor and Math.random is required. I'll look up what these things do (I'm incredibly new) – mujiha Nov 30 '16 at 02:27
  • `Math.floor(Math.random() * n)` is a standard way in JavaScript to generate a random number between `0` and `n`. `Math.random` generates a random float between `0` and `1`. `Math.floor` rounds a float down to the nearest integer. Example: `0.35856 * 6 = 2.15136` which then rounds down to `2`. – Rounin Nov 30 '16 at 09:23
0

console.log(array[Math.floor(Math.random() * (array.length - 1))]);
brigysl
  • 179
  • 1
  • 14