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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With