1

I got an array with some objects. Each object has an id. So when generating a new id, I want to check if an object with this id already exists. If there is an equal id, a new one should be generated.

generateId() {
    var records = store.getRecords(); // get all the objects
    var newId = getNewId(); // calculate a new id

    if (record.id == newId) // id already exists // record.id = id of the object
        newId = generateId(); // generate a new id
    else
        return newId; // return the id
}

getNewId() {
  // generate Id...
}

So how can I check all my records here if (record.id == newId) ? I use JQuery.

Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75
Question3r
  • 2,166
  • 19
  • 100
  • 200

3 Answers3

2

You can use a simple for loop for simlicity, it might not be efficient if you've got a lot of records obtained. If the structure of the object is the same for all records and assuming the data type of the object value matches the newId variable, this function will serve the purpose.

function DoesExist() {
   for(var i = 0; i < records.length; i++) {
     if(records[i].id == newId)
        return true;
   }

   return false;
}
Adrian
  • 8,271
  • 2
  • 26
  • 43
  • Your code should be maintanable. Otherwise there should exist a variables records and newId in a parent/global scope. You should pass them as function input parameters. – Sergej Aug 04 '17 at 08:54
  • 2
    @Sergej, This is an example, I am not providing code that one must use. OPs code isn't formatted properly either, hence the reason for my function that I put in place. – Adrian Aug 04 '17 at 08:56
1

The way I would go about it is to split my logic into multiple functions, so that I can check any new id against the existing ones. Then, wrapping this inside a loop, I could check generated values until one is found that is not in the array. For example (methods and values added for testing):

function generateId() {
  var records = store.getRecords(); // get all the objects
  var newId; 
  var isUnique = false; 
  while (!isUnique) { // check if unique, repeatedly
    newId = getNewId(); // calculate a new id
    isUnique = checkId(newId);
  }
  return newId; // return the id (is unique)
}
// Check if the id is unique against existing records
function checkId(newId) {
  var records = store.getRecords();
  for (var key in records)
    if (records[key].id == newId)
      return false;
  return true;
}

// Added for testing
function getNewId() {
  return Math.round(Math.random() * 10);
}
var store = {getRecords: function() {return [{id: 1}, {id: 2}, {id: 4}, {id: 6}];}}

// Actual testing
console.log(generateId());
Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75
1

this should work as incremental id generator:

const data = [{id: 1}, {id: 2}, {id: 3}, {id: 4}, {id: 5}, {id: 6}];

const exists = id => data.some(o => o.id === id);

const newId = (start = 0) => {
  const id = ++start;
  
  return exists(id) ? newId(id) : id;
};  


// you can also evaluate to implement some uid logic...
// there isn't much you can do on the client, but, 
// this could also help

const newUID = () => {
  const uid = Math.random().toString(32).substr(2);
  
  return exists(uid) ? newUID() : uid;
}

console.log({
  incrementalID: newId(),
  UID: newUID()
});
Hitmands
  • 13,491
  • 4
  • 34
  • 69
  • 1
    so `id => data.some(o => o.id === id)` should be the important part – Question3r Aug 04 '17 at 08:47
  • also, a recursive approach is the best for this case. – Hitmands Aug 04 '17 at 08:53
  • so for my case it should be `if (newId => records.some(record => record.id === newId))` right? I get a call stack exception but I think I made an mistake somewhere else – Question3r Aug 04 '17 at 08:55
  • your `call stack exception` could depend on [`maximum call stack hit`](https://stackoverflow.com/questions/7826992/browser-javascript-stack-size-limit#7828803), you might end up on an infinite loop... – Hitmands Aug 04 '17 at 08:58
  • It's a maximum callstack exception but I don't get the reason – Question3r Aug 04 '17 at 09:07
  • what's the code? Also, you've already set up the correct answer and that's should mean you've solved your problem... – Hitmands Aug 04 '17 at 09:08
  • Yes it's the "long way" and you showed up with a short one. The new code is https://hastebin.com/hajavagike.scala – Question3r Aug 04 '17 at 09:15