5

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?

Tuomas Toivonen
  • 21,690
  • 47
  • 129
  • 225
  • If it only needs to be unique for "as long as the program is running" then just implementing a counter would be a lot simpler and perform better than generating GUIDs. `var nextKey = (function() { var i=0; return function() { return i++; } })();` (You'd then just call `nextKey()` when you need an id.) – nnnnnn Aug 11 '16 at 07:59
  • I am extending your approach! You can try this. `function getUUID(){ var n = new Date().getTime(); var m = new Date(); var o = m.getMilliseconds(); var uuid = n * o; return uuid; }` –  Aug 11 '16 at 08:03
  • @MavenMaverick - That doesn't work for the same reason the OP's code doesn't work: if you call the function multiple times within the same millisecond you get the same result. – nnnnnn Aug 11 '16 at 08:05
  • How about using EPOCH `Date.now().toString(16)` it will be random and incrementing – Vinod Srivastav Mar 31 '23 at 12:34

1 Answers1

2

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/

Community
  • 1
  • 1
Marco Santarossa
  • 4,058
  • 1
  • 29
  • 49