Efficient Javascript search array for value using jQuery

There is a gap in my knowledge of JavaScript. I want to find an array of object values ​​for a specific value and return it.

During the year that I wrote JavaScript, I ran 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 everything 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.

+6
source share
4 answers

JQuery native function for this filter :

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

It is shorter than the code you have, and, more importantly, much more readable. As for efficiency, it will iterate over all the elements in the set to find as many matches as possible, but I hardly believe that this will be the neck of the bottle of your application, not focus on microoptimization .

I suggest you read Eric Lipper's blog about It's Faster .

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

 $.grep(data, function(ele){ retun ele.id == "foo"; }); 
+14
source

Another parameter using jQuery $.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 one, it's easy enough to return arr[0] if it exists.

+4
source

Although I'm not sure what the function should actually do (due to external context variables), the following should be more loop efficient

 var itemClicked = (function(){ var i, array = self.inventory.itemsArray, length = array.length; for( i=0; i < length; i++) { if(parseInt(array[i].id) === parseInt(idOfItem)){ return array[i]; } } return undefined; })(); 
0
source

This is an array of Javascript objects

Then do not use jQuery at all. At the very least, use $.each instead of creating a wrapper around the array. However, a simple for-loop is much shorter and more efficient:

 var itemClicked = (function(idnum) { var arr = self.inventory.itemsArray; for (var i=0, l=arr.length; i<l; i++) if (parseInt(arr[i].id, 10) === idnum) return arr[i]; })( parseInt(idOfItem, 10) ); 

You might also consider saving id properties as numbers right away, so you don't need to convert it every time.

0
source

All Articles