views:

35

answers:

1

how to search for the property of an object in an array , without using for loops in JavaScript ? If array is a simple one , I can use array.indexOf(value) to get the index but if array is array of objects ? other than looping any other way ?

e.g. ar = [{x,y},{p,q},{u,v}] if searched for v , it should return array index as 2.

+2  A: 

Searching for a value in an array typically requires a sequential search, which requires you to loop over each item until you find a match.

function search(ar, value) {
  var i, j;
  for (i = 0; i < ar.length; i++) {
    for (j in ar[i]) {  
      if (ar[i][j] === value) return i;
    }
  }
}

search([{'x': 'y'}, {'p': 'q'}, {'u': 'v'}], 'v'); // returns 2;
Daniel Vassallo
yep , that way I understand. I thought if there is some inbuilt functions to do the search , like we can sort an array depending on the objects property using array.sort() and compare function.
sat
@sat: Not really. These are the methods available for Arrays: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array. In JavaScript 1.6 there is the `filter()` method, but that would still be too complex for your requirement.
Daniel Vassallo
Thanks for the information.
sat