user2413244
user2413244

Reputation: 241

Check if variable exists in array of arrays

i need to get the array id and put this id number in the var pointerid = (id number from array);
i am using this code to store the cliked id from element:

jQuery('a').click(function(){
    var clickedId= $(this).attr("id");

now i want to search if 'element' : 'Equals to clickedId', if yes, get array id. for example:
clickedId= test
wp_button_pointer_array[1] = { 'element' : 'test'
so here 'element' : 'test' = clickedId (test) then give me the array id. array id here is 1

 var wp_button_pointer_array = new Array();
 wp_button_pointer_array[1] = {
     'element' : 'wp-button-pointer',
     'options' : {
         'content': 'The HTML content to show inside the pointer', 
         'position': {'edge': 'top', 'align': 'center'} 
     } 
 }; 
 wp_button_pointer_array[2] = { 
     'element' : 'some-element-id', 
     'options' : { 
         'content': 'The HTML content to show inside the pointer', 
         'position': {'edge': 'top', 'align': 'center'} 
     }
};

Upvotes: 0

Views: 95

Answers (3)

forgivenson
forgivenson

Reputation: 4435

This will return the index that contains the given element property.

function getIndexByElementId(elementArray, elementId) {
    var i, len;
    for(i = 0, len = elementArray.length; i < len; i++) {
        if(elementArray[i].element === elementId) {
            return i;
        }
    }
}

Upvotes: 0

kirinthos
kirinthos

Reputation: 452

I'm not really sure that I understand your question, but is this what you're trying to do?

function findElementIdByName(arr, name) {
  for (var i = 0; i < arr.length; i++)
    if (arr[i].element == name)
      return i;
  return -1; //not found
}

//example call with your data
var eleId = findElementIdByName(wp_button_pointer_array, 'some-element-id');

side note: array indexing starts at 0 in javascript, and you can use new Array(), but [] is slightly faster (~80ms on average comp) due to lexical parsing in the javascript interpreter

Upvotes: 1

tetta
tetta

Reputation: 445

var wp_button_pointer_array = [
    {
        'element' : 'wp-button-pointer',
        'options' : {
            'content': 'The HTML content to show inside the pointer',
            'position': {'edge': 'top', 'align': 'center'}
        }
    },
    {
        'element' : 'some-element-id',
        'options' : {
            'content': 'The HTML content to show inside the pointer',
            'position': {'edge': 'top', 'align': 'center'}
        }

    }
];


$('a').on('click', function(){
    var clickedId = $(this).attr("id");
    for(var i = 0; i < wp_button_pointer_array.length; i++ ) {
        if(wp_button_pointer_array[i].element === clickedId) {
            //do staff with wp_button_pointer_array[i]
        }
    }
});

Upvotes: 0

Related Questions