0

If I have an array;

var array = [item1, item2, item3, item4, item5];

How would I return every item once in order?

I tried the following but that returns the items randomly and it can repeat what it already displayed. But how do I get it so the items are not repeated?

var randomReturn = array[Math.floor(Math.random() * array.length)];
gusjap
  • 2,397
  • 5
  • 24
  • 38
hTeeML
  • 61
  • 8

4 Answers4

0
function getNext(arr) {
    return arr.splice(0, 1)[0];
}
function getRandom(arr) {
    return arr.splice(Math.floor(Math.random() * arr.length), 1)[0];
}

The first function returns in order, the second randomly. They never repeat an element, but they do modify the original array.

ralh
  • 2,514
  • 1
  • 13
  • 19
  • When I apply it to my code for some reason the second one still displays repeated, and the first one displays the first item in the array. – hTeeML Jul 31 '15 at 11:25
  • Perhaps I don't understand your exact use case. Try declaring an array, say, `var array = [1, 2, 3]`, and then use the functions, `getRandom(array)`. If you do it a couple of times, it will return a different element every time and never repeat. – ralh Jul 31 '15 at 11:27
0

using plain for loop and indexOf, you can filter out duplicates

  var array = [item1, item2, item3, item4, item5];
    var tempArray=[];

    for(var i=0;i<array.length;i++){
        if(tempArray.indexOf(array[i])){
         tempArray.push(array[i]);
        }
    }

console.log(tempArray);

And then if you want to return it in random order, shuffle it as mentioned in below answer.

How can I shuffle an array?

Define shuffle function defined in above answer and call it in your code.

shuffle(tempArray);
Community
  • 1
  • 1
Amit.rk3
  • 2,417
  • 2
  • 10
  • 16
0

How about removing the item from the array after you have returned it? This way the same value will only be returned once.

var array = ["item1", "item2", "item3", "item4", "item5"];

function getRandomItem(){
    var randomIndex = Math.floor(Math.random() * array.length);
    var returnValue = array[randomIndex]
    array.splice(randomIndex, 1);
    return returnValue;
}
gusjap
  • 2,397
  • 5
  • 24
  • 38
0

Please find below a method to return every item once, without repetition. After selection, each item is removed from the array and a new random selection is made on the remaining items.

I used this principle to randomize the entire array:

        var randomIndex
        var array = ["item1", "item2", "item3", "item4", "item5"];
        var randomArray = [];
        for (var i = 0, count = array.length; i < count; i++) {
            randomIndex = Math.floor(Math.random() * array.length);
            randomArray.push(array[randomIndex]);
            array.splice(randomIndex, 1);
        }
        document.querySelector('#out').innerHTML = JSON.stringify(randomArray, undefined, 4);
<pre id="out"></pre>
marianc
  • 439
  • 1
  • 4
  • 13