skip to Main Content
const randId = "comment_" + Math.floor(Math.random() * 1000);

const commentButton = document.createElement("section");
commentButton.id = randId;
commentButton.className = "comment2";

let IDArray = [];
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function addButtonClick() {
  if (numbers.length > 0) {
    randId;
    IDArray.push({ number: numbers++, id: randId });
    console.log(IDArray);
  }
}
addButtonClick();

Hello there, as you can see, randId generates a randomly generated Id and assigns this Id to my ‘commentButton’ element. I want to apply randId multiple times, so now I have many random Id’s. Now I want to add these to the IDArray and assign one number from the ‘numbers’ Array to each ID, e.g. the first generated ID is 204 and it gets assigned 1, the second one is 407 and it gets assigned 2, the third one gets number 3 and so on…I am stuck with this issue, does somebody know, how this could be done?

I tried assigning the ‘numbers’ element to the randId, but it just assigned all numbers on each generated Id

2

Answers


  1. Some of the things I am going to mention is already commented by our colleagues.
    Your randId is not a function it is a variable you assigned it a value once. you should make it a function which returns a value whenever its called.

    use some library like uuid to generate a unique id. if you want to avoid this, you can make an array with number generated within the function (which should come after "comment_") then check whether random generated IDs are already used and generate another one, in case it’s used.

    See my code

    const usedIds = [];
    
    
    const uniqueId = () => {
      let num;
      do {
        num = "comment_" + Math.floor(Math.random() * 1000);
      } while (usedIds.includes(num));
      
      usedIds.push(num);
      return num;
    };
    
    
    
    function addButtonClick() {
      if (numbers.length > 0) {
        const randId = uniqueId();
        IDArray.push({ number: numbers.shift(), id: randId });
        console.log(IDArray);
      }
    }
    
    Login or Signup to reply.
  2. You need to make randId a function as shown and then you can use a for-of loop on numbers to generate the random ids as shown:

    const randId = () => "comment_" + Math.floor(Math.random() * 1000);
    const IDArray = [];
    const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    function addButtonClick() {
      for(const number of numbers) {
        const id = randId();
        IDArray.push({ number, id });
        console.log(IDArray);
      }
    }
    
    addButtonClick();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search