absynthe minded web smith absynthe minded web smith - 1 month ago 4
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

is an option, cuz I can't put a variable in

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")',
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 am I going wrong?


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

    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.