Legend
Legend

Reputation: 116990

Explode a string into a hashmap for searching?

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.

Upvotes: 1

Views: 308

Answers (2)

Pablo Fernandez
Pablo Fernandez

Reputation: 105258

"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;
  }
}

Upvotes: 2

SimonJ
SimonJ

Reputation: 21306

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"); }

Upvotes: 2

Related Questions