1

I want to choose a random ID from the list of available IDs. After choosing, I want to check if there is an item with that ID, if there is no, then I want to add there. If it exists then I want to generate the ID again till it chooses an ID which does not exist.

Problem:

Currently I'm using if statement to check if an ID exists, if it exists then it generates again. However the problem is that it only checks once.

It is possible that newly chosen ID also exists, therefore I would like to keep checking until it finds some ID which doesn't exist. For that I would need to use a loop, but I'm unable to figure out how to do that because the items are added dynamically.

Here's what I have tried:

HTML:

<input type="button" id="button" value="Add new" />

<ul class="items">
  <li id="a4">item with id a4</li>
  <li id="c2">item with id c2</li>
  <li id="c3">item with id c3</li>
  <li id="a1">item with id a1</li>
</ul>

Javascript:

function randID () {
    var arr = new Array("c1", "c2", "c3", "c4", "a1", "a2", "a3", "a4","a5","a6");
    var index = Math.floor(Math.random()*(arr.length));
    return arr[index];
}

$('#button').click(function() {

   var newID = randID();

   if ( $('.items').find('#'+newID).length > 0 ) {
      var newID = randID();   
   } 

   $('.items').append('<li id="'+newID+'">item with id '+newID+'</li>');

});

JSFiddle: https://jsfiddle.net/o4uL6gaj/

Zach
  • 25
  • 4

6 Answers6

2

The whole idea of looping and checking if an id is taken creates a performance bottleneck.

I would suggest generating seemingly random id's, e.g. Create GUID / UUID in JavaScript?

if you really need to take an id from the list, remove the id from the list once it is used. E.g.

var listOfIDs = ['id1', 'id2',.., 'idn'];
function getNewRandomId()
{
   var n = Math.floor(Math.random()*(listOfIDs.length));
   return listOfIDs.splice(n,1);
} 
Eriks Klotins
  • 4,042
  • 1
  • 12
  • 26
1

I would suggest replacing the if with while, but you need an additional condition to make sure it won't go infinite once every item has been added. Maybe a return first thing in the function if you already have every items ?

Morphyish
  • 3,932
  • 8
  • 26
1

The thing you want to do is to use a while loop like so:

$('#button').click(function() {
   var newID = randID();
   var found = $('.items').find('#'+newID).length > 0;
   var trys = 0;
   while (found && trys < 10){
       newID = randID();
       found = $('.items').find('#'+newID).length > 0;
       trys++;
   }    
   $('.items').append('<li id="'+newID+'">item with id '+newID+'</li>');

});

However, I would recommend tracking the used IDs in an data element, and only chose a random one from the remaining possible Ids.

var possibleIds = new Array("c1", "c2", "c3", "c4", "a1", "a2", "a3", "a4","a5","a6");

function randID () {
    var index = Math.floor(Math.random()*(possibleIds.length));
    return possibleIds[index];
}

$('#button').click(function() {
    // check if there are any possible Ids
    if(possibleIds.length > 0){
        var newID = randID();
        $('.items').append('<li id="'+newID+'">item with id '+newID+'</li>');
        // remove used Id from possibleIds
        possibleIds = possibleIds.filter((id) => id !== newID);
    }else{
        console.log("no id left!");
    }
});
Danmoreng
  • 2,367
  • 1
  • 19
  • 32
0

try use while

var newID = randID();

   while ($('.items').find('#'+newID).length > 0 ) {
      var newID = randID();   
   } 



 $('.items').append('<li id="'+newID+'">item with id '+newID+'</li>');
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33
0

Just check the Id exists using length.

if($('#myid').length==0)
{
//Create the Item
}
Sandeep Thomas
  • 4,303
  • 14
  • 61
  • 132
0

use a while loop

function randID () {
    var arr = new Array("c1", "c2", "c3", "c4", "a1", "a2", "a3", "a4","a5","a6");
    var index = Math.floor(Math.random()*(arr.length));
  return arr[index];
}

function createItem(){console.log("createItem");
    var newID = randID();
  console.log($('.items').find('#'+newID).length);
   if ( $('.items').find('#'+newID).length > 0 ) {
        console.log("generated again. Old id was " + newID);    
        return 0;
   }
   else{
    return newID;
   }

}

$('#button').click(function() {  
   var newID = 0;
   while(newID==0){
    newID = createItem();
   }

   $('.items').append('<li id="'+newID+'">item with id '+newID+'</li>');

});
Ehcnalb
  • 466
  • 4
  • 16
  • `while((newID=createItem())==0) {}` but would be better if it was just `newID=createItem()` and the while loop was in createitem – freedomn-m Aug 01 '19 at 09:50