-1

Assume you have an array:

var arrStateCityAll=['CA_Alameda','CA__Pasadena','CA_Sacramento','NY_Albany','NY_Buffalo','NY_Ithaca']

Is there an easy way using javascript and/or jQuery to filter the arrStateCityAll to get a new array (a subset of arrStateCityAll); something like this:

// return's ['CA_Alameda','CA__Pasadena','CA_Sacramento']

var arrStateCityCA=FilterArray('CA',arrStateCityAll);

5 Answers 5

5

Likely you want to do a regex on each item. You can do this with jQuery's grep function.

http://api.jquery.com/jQuery.grep/

Sign up to request clarification or add additional context in comments.

Comments

3

You can use javascript's Array.filter.

var arrStateCityAll = ['CA_Alameda','CA__Pasadena','CA_Sacramento','NY_Albany','NY_Buffalo','NY_Ithaca']

var arrStateCityCA = arrStateCityAll.filter( function (element) {
    return element.indexOf("CA_") == 0;
});

The mozilla documentation linked to above has a solution for browsers that don't implicitly support filter.

2 Comments

@user815460 That's why you should use $.grep :)
2

This should work.

var arrStateCityCA = [];
for (var i = 0;i<arrStateCityAll.length;i++){
    if (arrStateCityAll[i].substr(0,2) == 'CA'){
        arrStateCityCA.push(arrStateCityAll[i]);
    }
}

Comments

2

You could use jQuery.grep

var arrStateCityCA = 
   $.grep(arrStateCityAll,function(el,i){return (el.substring(0,2)=='CA')});

Demo at jsfiddle

To implement you actual FilterArray function as shown in your post you could do

function FilterArray(state,arr){
    return $.grep(arr,
                  function(el,i) {return (el.substring(0,2)==state)}
    );
}

This makes a few assumptions.

  1. State is always 2 chars.

  2. State is always the first 2 chars.

And of course remember case-sensitivity (this function is case sensitive) ie 'CA' not equal to 'Ca'.

Comments

1

if you are going to have an undescore between your state and city name, you can split on the underscore and test against the first array value

function getSubSetByState(set,state) {

    var result = [];
    for(var i=0,l=set.length;i<l;++i) {
        if(set[i].split('_')[0] === state) {
            result.push(set[i]);
        }
    }

    return result;
}

Use if by giving it the set of places, and then the state you are searching for.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.