0

I have for loop that alerts strings from array, I wonder how can I alert them randomly, so it will run gamesNames.length times and display them in different-random order each time (without duplicating them) in JavaScript ?

  for (var i = 0; i < gamesNames.length; i++) {
            alert (gamesNames[i].Name + gamesNames[i].year );
        }

3 Answers 3

1

here is a Link http://www.javascriptkit.com/javatutors/arraysort.shtml to the main idea, in Javascript

and here is the Code

...
gamesNames.sort(function() {return 0.5 - Math.random()}) ;
for (var i = 0; i < gamesNames.length; i++) {
      alert (gamesNames[i].Name + gamesNames[i].year );
}
...

I hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

1

Create an array with items that contain an index and a random number. Shuffle them by sorting on the random number, and use the index to alert the items:

var idx = [];
for (var i = 0; i < gamesNames.length; i++) {
  idx.push({ idx: i, rnd: Math.floor(Math.random() * 100000) });
}
idx.sort(function(x,y){ return x.rnd - y.rnd; });
for (var i = 0; i < idx.length; i++) {
  var j = idx[i].idx;
  alert (gamesNames[j].Name + gamesNames[j].year);
}

Comments

1

You can use a while-loop for this easily, in combination with array.splice:

var array = ["1", "2", "3", "4"];
while(array.length > 0)
{
    // Get a random index
    var index = Math.floor(Math.random() * array.length);
    // Append it to the DOM (or do whatever you want with it)
    $("body").append($("<p />").html(array[index]));
    // Remove it from the array
    array.splice(index, 1);
}

JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.