简体   繁体   中英

How to make sure an item doesn't get pushed into an array twice?

I want to display four random images on my page, therefore first I am creating a random image from an initial array of images:

function randomFlag() {
var randomFlag = Math.floor(Math.random() * flags.length);
return flags[randomFlag];
}

Then I am pushing four random images into a new array:

function generateRandomFlag(num) {
var arr = [];
for (var i = 0; i < num; i++) {
    arr.push(randomFlag());
}
return arr;
}

The problem I'm having is that sometimes I am getting the same image pushed twice into the array and eventually having two or more of the same image displayed instead of having four random Images.

How can I create the functionality to first check if the image already exists in the array, and push it only if it doesn't exist there already?

Thanks.

Alternative approach is to use all flags, shuffled randomly

function generateRandomFlag(num) {
    return flags
    .slice() // copy the flags array because .sort mutates the source array
    .sort(function() { return Math.random() - 0.5; }) // shuffle the copied array
    .slice(-num); // get the LAST "num" values of the shuffled array
}

In ES2015+ it's even more succinct

const generateRandomFlag = num => flags.slice().sort(() => Math.random() - 0.5).slice(-num);

You could either refactor generateRandomFlag or randomFlag . In my case I will refactor generateRandomFlag .

function generateRandomFlag(num) {
  var arr = [];
  var reachNum = false;
  var ctr=0;
  while (!reachNum) {
    var flag = randomFlag();
    if (arr.indexOf(flag)==-1)
    {
      arr.push(flag);    
      ctr++;
    }
    if (ctr==num)
       reachNum = true;
  }
 return arr;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM