Skip to content
Advertisement

JQuery – Adding random numbers to an array and then checking if there are repetitions before printing array

I’m trying to write a “for” loop that will go through a list of 30 songs in an array and then print a list of 20 random items in that array with no repetitions.

var items = [];
var songList = [];
var pastSongs = [];

for (i = 1; i <= 30; i++) {
  items.push("song" + i);
}


$(".btn").click(function getRandom() {

  for (g = 1; g <= 20; g++) {

    var randomItem = (items[Math.floor(Math.random() * items.length)]);

    $("h2").text(randomItem);

    songList.push(randomItem);


    if (pastSongs.includes(randomItem)) {
      $("p").text("repeat");
    } else {
      $("p").text(songList);
      (pastSongs).push(randomItem);
    }

  }

});

Advertisement

Answer

If I only focus on the question title.

Adding random numbers to an array and then checking if there are repetitions before printing array

Aside the “assumed” use case where the suggested duplicate about “shuffling an existing array” would be quite good. If you want to create an array of unique numbers having an amount length of values between a min and a max, Here is how:

function getArrayOfuniqueRandomNumbers(min, max, amount) {
  let result = [];

  if (amount !== undefined && amount < max - min) {
    while (result.length < amount) {
      let randomNumber = Math.floor(Math.random() * (max - min));
      if (result.indexOf(randomNumber) == -1) {
        result.push(randomNumber);
      }
    }
  }

  return result;
}

// So here, you request an array of 20 numbers between 0 and 30
console.log(getArrayOfuniqueRandomNumbers(0,30,20))

The function will return a non-empty array if the requested amount is possible given the min and max.

There is a condition to avoid an infinite loop of the while. So if the provided arguments do not allow to find the required amount of unique numbers, it will return an empty array.

How it works:

while the amount is not reached, keep on trying to add a new random number.

The numbers are added to the array to be returned only if not already present because of the .indexOf() check.

Do whatever you wish with the returned array.

Advertisement