Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get purely unique number in javascript [duplicate]

I must create unique keys for certain objects I create (needed for React key prop), where key can be any random string or number, but has to be truly unique for each time it's generated in program lifetime.

I tried to use new Date().getTime() as key, but encountered problem where multiple objects got assigned the same key when creating them in loop.

Is there a function which returns something purely unique each call as long as the program is running, or do I have to implement my own counter?

like image 907
Tuomas Toivonen Avatar asked Oct 30 '22 22:10

Tuomas Toivonen


1 Answers

You can create a UUID:

function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

Original answer: https://stackoverflow.com/a/105074/5109911

alternative: https://jsfiddle.net/briguy37/2MVFd/

like image 124
Marco Santarossa Avatar answered Nov 12 '22 13:11

Marco Santarossa