absynthe minded web smith absynthe minded web smith - 3 months ago 10
jQuery Question

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?

Answer

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.