1

I have a javascript array like this

   var open_chats = [];
   open_chats.push({
    "chatid": 'dfsfsdfsdf',
    "data": 'adfsdf'
   });

I need to check if an item exists in this array, I am using something like this.

    if ($.inArray('dfsfsdfsdf', open_chats) !== -1){
    alert('contains');
    }

Except this does not seem to work. I cant quite find something that will work for this array. Can anyone help?

juphilli
  • 13
  • 4

2 Answers2

0

As you are having objects, not strings in your array I would suggest to use jQuery's grep method:

var result = $.grep( open_chats, function( data ){ return data.chatid == 'dfsfsdfsdf'; });

if( result.length ) {
    alert('contains');
}
antyrat
  • 27,479
  • 9
  • 75
  • 76
  • This works, but `$.grep` is going to build a new array containing all matches, whereas `Array.prototype.some` will loop through until one match is found and stop. If you don't need that result array, that's not the best option. – Jacob Jan 10 '15 at 19:20
  • Yes, but `Array.prototype.some` not working in old IE browsers ( e.g < 9 ) – antyrat Jan 10 '15 at 19:23
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some Lists a polyfill for `Array.prototype.some` – Alexander Kerchum Nov 14 '15 at 00:57
0

Your code is checking if 'dfsfsdfsdf' is in the array, not if an object with a property of chatid has 'dfsfsdfsdf' as its value.

Using native JavaScript array methods:

var hasMatch = open_chats.some(function(chat) {
    return chat.chatid === 'dfsfsdfsdf';
});
if (hasMatch) {
    alert('contains');
}
Jacob
  • 77,566
  • 24
  • 149
  • 228