JavaScript: match variable to element in array of arrays

I get the first two variables loaded from the backend, then I want to match the brand name I get back and return a two letter code. I put the associated brands in an array of arrays.

It doesn't seem match() is an option, cuz I can't put a variable in regExp().

This didn't work:

if (brand.indexOf(brand_code[i])) {
    bc = brand_code[i][1];
}

This didn't work.

if (brand_code[i][0]===brand)
    bc = brand_code[i][1];
}

This is my latest attempt.

$(document).ready(function() {
    var phone_model='$request.getHeader("x-wurfl-model-name")',
        brand='$request.getHeader("x-wurfl-brand-name")',
        brand_code=[
            ['Alcatel','AL'],
            ['Huawei','HU'],
            ['LG','LG'],
            ['Motorola','MT'],
            ['Samsung','SA'],
            ['Unimax','UX'],
            ['ZTE','ZE']];
    for (var i = brand_code.length - 1; i >= 0; i--) {
        if ($.inArray(brand,brand_code[i])) {
            bc = brand_code[i][1];
        }
    }
    $('.faq .mobile_tutorial a').append(bc+phone_model);
});

This gives me an error of Cannot read property '3' of undefined Where phone_model='Z990g' & brand='ZTE'

Where am I going wrong?

Upvotes: 0

Views: 256

Answers (2)

trincot
trincot

Reputation: 350272

If you would structure your data differently in the variable brand_code, it would become a bit easier:

    brand_code={
        'Alcatel':'AL',
        'Huawei':'HU',
        'LG':'LG',
        'Motorola':'MT',
        'Samsung':'SA',
        'Unimax':'UX',
        'ZTE':'ZE'
    };
    bc = brand_code[brand];
}

This will not need to go through an array. Most JavaScript engines find the match in constant time if you use the object-based lookup above. In ES you can use a Map for the same purpose and with the same efficiency.

About your attempt

$.inArray returns 0 when ZTE matches the first element of an array, so the if condition would be false in that case. But worse, when ZTE is not found, the method returns -1, which makes the if condition true.

So, you would have had better results if you had put:

if ($.inArray(brand,brand_code[i])>-1) {

From the jQuery documentation:

The $.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, $.inArray() returns 0.

Upvotes: 2

Rob M.
Rob M.

Reputation: 36511

Use Array.filter to find your match, then you can either check that the result's length > 0 and get result[0][1] from it, or use Array.reduce to return only the code:

// filter down to match and reduce the match to it's code value
brand_code.filter(function(pair) { 
    return pair[0] === brand 
}).reduce(function(out, match) { 
    return match[1]; 
}, '');

OR ES6:

brand_code.filter(pair => pair[0] === brand)
          .reduce((_, match) => match[1], '');

Upvotes: 2

Related Questions