tags:

views:

44

answers:

2

I have a string like this being returned from my backend:

"1,2,3,4,5,6"

I have a large array locally and want to display only those items not in this list, so I was thinking of exploding this string into an array but how can I search efficiently? As far as I know there are no hashmaps in JS so how does one do this? I just need to check for key existence.

+1  A: 
"1,2,3,4,5,6".split(",").some(function(letter) { 
  return letter === '2' 
});

Warning: Might not work in IE (or other crappy browser)

Cross browser version (that relies on native code for performance):

var arr = "1,2,3,4,5,6".split(",");
if(arr.some)
{
  arr.some(function(letter) { 
    return letter === '2' 
  });
}
else
{
  for(var i  = 0 ; i < arr.length ; i++ )
  {
      if(arr[i] === '2') return true;
  }
}
Pablo Fernandez
@Pablo Fernandez: +1 Thanks but I was looking for a cross-browser solution... Need to support crappy ones as well unfortunately :)
Legend
There you go! fast and improved crappy-browser ready solution :)
Pablo Fernandez
+1  A: 

All Javascript objects are also hash tables that can store string or numeric keys:

var x = {};
x["foo"] = 1;
if("foo" in x) { alert("hello!"); }
if("bar" in x) { alert("should never see this"); }
SimonJ
True, but does not answer the real question (check for a number existence in the given string)
Pablo Fernandez
@SimonJ: Thanks. I will adapt this for my need.
Legend