Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

If I have the following array of objects:

[ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 2, username: 'ted' } ]

Is there a way to loop through the array to check whether a particular username value already exists and if it does do nothing, but if it doesn't to add a new object to the array with said username (and new ID)?

Thanks!

share|improve this question
    
Are Bill and Ted supposed to have the same ID? –  user2357112 Apr 3 at 17:18
    
Why there's two elements with the same id? Is that possible that elements will be removed from this array, or can we be sure that the new element will always have id equal to arr.length + 1? –  raina77ow Apr 3 at 17:18
    
If you don't want to loop through it, check this Q&A for extending array prototype, stackoverflow.com/questions/1988349/…. –  CemOzer Apr 3 at 17:19

3 Answers 3

up vote 3 down vote accepted

I've assumed that ids are meant to be unique here. some is a great function for checking the existence of things in arrays:

function checkAndAdd(name) {
  var id = arr.length + 1;
  var found = arr.some(function (el) {
    return el.username === name;
  });
  if (!found) { arr.push({ id: id, username: name }); }
}

Fiddle

share|improve this answer
1  
Thanks Andy this is a very clean solution to the problem and is working very well. I had not come across the some method before. Your assumption was correct my ID example was just a typo, I was using arr.length + 1 to determine the ID. –  user2576960 Apr 4 at 8:19

It's rather trivial to check for existing username:

var arr = [{ id: 1, username: 'fred' }, 
  { id: 2, username: 'bill'}, 
  { id: 3, username: 'ted' }];

function userExists(username) {
  return arr.some(function(el) {
    return el.username === username;
  }); 
}

console.log(userExists('fred')); // true
console.log(userExists('bred')); // false

But it's not so obvious what to do when you have to add a new user to this array. The easiest way out - just pushing a new element with id equal to array.length + 1:

function addUser(username) {
  if (userExists(username)) {
    return false; 
  }
  arr.push({ id: arr.length + 1, username: username });
  return true;
}

addUser('fred'); // false
addUser('bred'); // true, user `bred` added

It will guarantee the IDs uniqueness, but will make this array look a bit strange if some elements will be taken off its end.

share|improve this answer
    
Thanks for this. I went with Andy's solution in the end because it's a more succinct way of achieving the same thing. I won't be removing users at any point so IDs should remain consistent. The check allows users to log in, out and back in again without the array growing overtime. Just for info I'm using this function in conjunction with passport.js and I haven't been able to find a way of removing users from the array without playing with passport code itself. This solution works nicely. –  user2576960 Apr 4 at 8:28

I like Andy's answer, but the id isn't going to necessarily be unique, so here's what I came up with to create a unique ID also. Can be checked at jsfiddle too. Please note that arr.length + 1 may very well not guarantee a unique ID if anything had been removed previously.

var array = [ { id: 1, username: 'fred' }, { id: 2, username: 'bill' }, { id: 3, username: 'ted' } ];
var usedname = 'bill';
var newname = 'sam';

// don't add used name
console.log('before usedname: ' + JSON.stringify(array));
tryAdd(usedname, array);
console.log('before newname: ' + JSON.stringify(array));
tryAdd(newname, array);
console.log('after newname: ' + JSON.stringify(array));

function tryAdd(name, array) {
    var found = false;
    var i = 0;
    var maxId = 1;
    for (i in array) {
        // Check max id
        if (maxId <= array[i].id)
            maxId = array[i].id + 1;

        // Don't need to add if we find it
        if (array[i].username === name)
            found = true;
    }

    if (!found)
        array[++i] = { id: maxId, username: name };
}
share|improve this answer
    
I like the simplicity in the other answers, I just posted mine to add the check for unique ID –  Uxonith Apr 3 at 17:28
    
Thanks for your answer Uxonith. At the moment I do not have a need for unique ID because I won't be removing users from the array. I will keep this resolution in my back pocket in case the need arises. Thanks again –  user2576960 Apr 4 at 8:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.