S16
S16

Reputation: 2995

Use array instead of object in JavaScript

I have the following var:

    filter =  {
            "country": 1,
            "Age Group": {},
            "Gender": {},
            "NEWSEC": {},
            "Telco_Segment": {}
    };

and function:

function facetBuilder(key, val)
{
    if(key == 'country')
    {   
        filter.country = val;
    }
    else
    {
        if(typeof filter[key][val] !== "undefined" )
        {
            delete filter[key][val]; //I'm assuming you want to remove it
        }
        else
        {
            filter[key][val] = true;
        }
    }

    console.log(filter);
}

The resulting object ends up looking something like this:

    filter =  {
            "country": 1,
            "Age Group": {
                4: true,
                3: true,
                2: true
            },
            "Gender": {
                1: true
            },
            "NEWSEC": {
                3: true,
                2: true
            },
            "Telco_Segment": {}
    };

but what I really want is something like this:

    filter =  {
            "country": 1,
            "Age Group": [4,3,2],
            "Gender": [1],
            "NEWSEC": [3,2],
            "Telco_Segment": []
    };

And I'm not sure how to approach it.

Upvotes: 0

Views: 1194

Answers (2)

dbkaplun
dbkaplun

Reputation: 3648

What you have now, if(typeof filter[key][val] !== "undefined" ), is good, because objects have constant-time lookups. If you use an array scan, if(filter[key].indexOf(val) !== -1), the time complexity increases to O(n) because you'd have to scan each element to see if it's in the array.

Upvotes: 0

Marc B
Marc B

Reputation: 360782

Instead of

filter[key][val] = true;

how about

filter[key].push(val);

and

filter =  {
    "country": 1,
    "Age Group": [],
                 ^^---empty array, instead of {} for object.

Upvotes: 4

Related Questions