Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript efficient search array for value with jQuery

There's a gap in my JavaScript knowledge here. I want to search an array of objects values for a particular value and return it.

For the year I have been writing JavaScript, I have been implementing it like this:

var itemClicked = (function(){

  var retval;

  //Note self.inventory.itemsArray is an array of JS objects

  $(self.inventory.itemsArray).each(function(i){
    if(parseInt(this.id) === parseInt(idOfItem)){
      retval = this;
      return false;
    }
  });

  return retval;

})();

It works, but I'm sure as anything there is a more elegant way. Tell me please!

EDIT - Solution

Thanks to @gdoron with his answer below.

var myVar = $(self.owner.itemsArray).filter(function(){
   return parseInt(this.id) == parseInt(recItemID);
}).get(0);

Note: .get(0) was added at the end because myVar is wrapped as a jQuery object.

like image 674
Adam Waite Avatar asked Jan 09 '13 22:01

Adam Waite


2 Answers

The native jQuery function for this is filter:

$(data).filter(function(){
    return this.id == "foo";
});

It's shorter than code you have and more important a lot more readable.
About efficiency, it will iterate all the elements in the set to find as much as possible matches, but I hardly believe it will be the bottle neck of your application, don't focus on micro-optimisations.

I suggest you read Eric Lipper blog about Which is faster.

You can also use grep as suggested by @Mattias Buelens:

$.grep(data, function(ele){
    retun ele.id == "foo";
});
like image 198
gdoron is supporting Monica Avatar answered Oct 03 '22 18:10

gdoron is supporting Monica


Just another option using jQuery's $.grep( ) function

var arr = $.grep( self.inventory.itemsArray, function ( n ) { 
    return n.id == idOfItem;
});

The above returns an array of matching array elements. If you just want the first it is easy enough to return arr[0] if it exists.

like image 26
Bruno Avatar answered Oct 03 '22 17:10

Bruno