-2

I want to test if a local_key already exists, if it exists generate another local_key and check again

// Here I go throught an object and try to return a index
const local_key = messagesRow.map((message, key) => {
    return message.local_key;
}).indexOf(message.local_key);

// If it returns 0 or bigger, it means that the local_key already exists
if(local_key >= 0){
    message.local_key = Math.floor(Math.random() * 9999);
}

EDIT I want to recheck every time, cause if the local_key exists and I generate another one, this new local_key maybe exists too

SpaceDogCS
  • 2,808
  • 3
  • 20
  • 49

2 Answers2

1

This will work, but you are iterating over the whole array, where you only need one match. I would recommend to use some javascript library like underscore (http://underscorejs.org/) which provides nice find function.

Using random number from 0 to 99999 is not a good solution - there is probability that you will generate duplicate number. Better choice would be some UUID / GUID (see duscussion here: Create GUID / UUID in JavaScript? ) - and there will be no need at all to search for it in array as this is unique

Konstantin Pribluda
  • 12,329
  • 1
  • 30
  • 35
0

The best way to generate a key is using uniqid

$id = md5(uniqid(date('d/m/Y H:i'), true));
SpaceDogCS
  • 2,808
  • 3
  • 20
  • 49