Reputation: 12138
I have a javascript array that looks like this:
myFields = [
["fb-method","drop",false,"How did you order?"],
["fb-date","calendar",false,""],
["fb-time","drop",false,""],
["fb-location","drop",false,""],
["fb-amount","text default",false,""],
["fb-share","drop",false,""],
["fb-msg","textarea",true,""],
["next-btn","button",true,""]
]
I'm able to loop through the array and deal with specific bits like this:
len = fields.length;
//first check to make sure required fields are filled in
for(i=0; i<len; i++) {
a = fields[i];
if(a[0] != "fb-method") {
// do stuff
}
}
I need to be able to (outside the loop) do something if a specific element isn't part of the array, specifically one that looks like this:
["fb-location","drop",false,""]
I've tried using jQuery's .inArray
function, but it returns true even when it should return false. See fiddle here.
What's the best way to go about this? jQuery or standard js is fine.
Upvotes: 1
Views: 115
Reputation: 122906
Besides $.inArray
you could use Array.filter
on tmp
this way:
if( tmp.filter(function(a) {return -~a.indexOf('fb-location');}).length ) {
// exists
}
See also: Array.filter, Array.indexOf
Using JQuery, you'd use the JQuery grep
method
if( $.grep(tmp,function(a) {return -~a.indexOf('fb-location');}).length ) {
// exists
}
Upvotes: 0
Reputation: 40459
$.inArray
does not return a bool, it returns the index (if no match exists, it returns -1
). You would want this statement (based on your jsfiddle):
if(jQuery.inArray("fb-location", tmp) > -1) {
alert("it exists");
}
else {
alert("it doesn't exist");
}
DEMO: http://jsfiddle.net/azWLC/2/
UPDATE:
As mentioned in the comments, this is only a half solution since the array is multidimensional. I recommend first using $.map()
:
var tmp = [
["fb-method","drop",false,"How did you order?"],
["fb-date","calendar",false,""],
["fb-time","drop",false,""],
["fb-amount","text default",false,""],
["fb-share","drop",false,""],
["fb-msg","textarea",true,""],
["next-btn","button",true,""]
];
var values = $.map(tmp, function(n, i){
return n[0];
});
if(jQuery.inArray("fb-location", values) > -1) {
alert("it exists");
}
else {
alert("it doesn't exist");
}
DEMO: http://jsfiddle.net/azWLC/4/
Upvotes: 6
Reputation: 1523
jquery.inArray returns the index of the element. If it is not found it returns -1.. And any number except 0 is true and hence it says 'it exists'
Upvotes: 0