Miura-shi
Miura-shi

Reputation: 4519

Finding Value in Array

I am trying to find if an object contains a certain value and then have that dictate the next steps of the operation. This is an object that is returned from Google Maps API. This is an exact example returned back from their API.

Array

[{'long_name': 'United States', 'short_name': 'US'}, {'long_name': 'California', 'short_name': 'CA'}];

Conditional/Check

if( $.inArray('US', array) == -1 ){

    alert('Your country is not supported.');

} else {
     alert('Your country is supported.');   
}

This doesn't work because it only looks at the index, and not values I believe. What's the cleanest and fastest way to find and return if the value exists in the array?

Upvotes: 0

Views: 71

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173522

To find a match you could use jQuery.grep():

var res = $.grep(arr, function(item) {
    return item.short_name == 'US';
});

It returns an array, which will be empty if there are no matches found.

Alternatively, you could use Array.prototype.filter():

var res = arr.filter(function(item) {
    return item.short_name == 'US';
});

Bonus

You can generalise it further:

function searchFunction(field)
{
    return function(arr, term) {
        return arr.filter(function(item) {
            return item[field] == term;
        };
    };
}

var searchByShortName = searchFunction('short_name');

if (searchByShortName(arr, 'US').length) {
    // ..
}

Upvotes: 5

3coins
3coins

Reputation: 1342

What you need is something like this

var countries = [{'long_name': 'United States', 'short_name': 'US'},
{ 'long_name': 'California', 'short_name': 'CA'}]; //now this is an array with objects

function hasCountry(shortName){
    for(var i = 0, len = countries.length; i < len; i++){
        if(countries[i]['short_name'] === shortName) return true;
    }
    return false;
}

if(hasCountry('US')){
   // not supported..
} else {
   // not supported
}

However, a better solution would be normalize the countries to an object like this.

var countries = {'US': 'United States', 'CA': 'California'}; // this is an object

if(countries['US'] != null){
    // supported
} else {
  // not supported
}

Upvotes: 1

Related Questions