7

I was wondering if anyone knows of a way to use the JQuery find method or inArray method to find an item in an array. I can't seem to find anything in the docs.

for example:

var items = [{id:1, name:'bob'}, {id:2, name:'joe'}, {id:3, name:'ben'}];
var found = $(items).find("[name='ben']");

or

var items = [{id:1, name:'bob'}, {id:2, name:'joe'}, {id:3, name:'ben'}];
var found = $.inArray("[name='ben']", items);
bendewey
  • 39,709
  • 13
  • 100
  • 125

2 Answers2

3

I think what you are looking for is the RichArray plugin and more specifically

$.RichArray.filter()

You can grab it at RichArray

Sarat
  • 1,608
  • 12
  • 10
  • 1
    The in method returns a boolean and i really need the index or preferably the item itself. – bendewey Jan 05 '09 at 18:33
  • nor does the in method look much different than the inArray method of the jQuery/Utilities – bendewey Jan 05 '09 at 18:35
  • 1
    The Filter function worked on the richArray plugin. var filtered = $.richArray.filter(items, function(item) { if (item[attr] == name) { return true; } return false; }); if (filtered.length == 0) { return null; } return filtered[0]; – bendewey Jan 05 '09 at 20:07
0

The jQuery find method operates on the DOM. If you try to search an array, you'll probably hit this code:

// check to make sure context is a DOM element or a document
if ( context && context.nodeType != 1 && context.nodeType != 9)
    return [ ];

That can be found in the jQuery source for the find method. It always returns an empty array if you are not using a DOM element or the document as your context.

EndangeredMassa
  • 17,208
  • 8
  • 55
  • 79