0

I have a array of objects say items. I want to find item having name xyz.

Currently, I wrote a for loop

for(var i = 0; i < items.length; i++)
{
    if( items[i].name == "xyz" ) 
    {
        found = true;
        break;
    }
}

Is it possible to shorten this loop to one line statement using jquery? something like this:

$.find(items, "name", "xyz");
1
  • 2
    @huMptyduMpty: No, that's just indexOf. Commented Dec 14, 2012 at 12:09

6 Answers 6

1

You might use

var matchingItems = items.filter(function(v){return v.name=="xyz"});

or using jQuery (for greater compatibility, as like many Array functions, filter or some aren't available on IE8) :

var matchingItems = $.grep(items, function(v){return v.name=="xyz"});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a ton! this is very neat and efficient.
@KevindraSingh: Don't you want to return a boolean value instead of an array?
I want the item object. it's returning the same.
1

Something like:

$.grep(yourArray, function(n) { 
    return n.name == "xyz"; 
});

Comments

0

Use the native some method:

items.some(function(el) { return el.name == "xyz"; })

With jQuery, you would need to do something like $.grep and then check the length ($.grep(items, function(el){ return el.name=="xyz"; }).length > 1) - not an optimal solution. If you want to use a library solution for those browsers that don't support some (and don't want to use the polyfill), use Underscore's any.

3 Comments

some isn't available on IE8.
@dystroy: I already mentioned two solutions for buggy browsers.
Those mentions weren't there when I commented. It seems this is still a needed precision.
0
    var arr = ["abc", "xyz" ];
        if($.inArray("abc",arr) > 0){
          return true;
        }
else 
return false

this will return the index of "searching string"

if not found, it will return -1.

Comments

0

Use jQuerys inArray Example

http://api.jquery.com/jQuery.inArray/

might helps you

Comments

0
(function( $ ) {
    $.find = function( array, property, key ) {
        var found = false;
        for(var i = 0; i < array.length; i++)
        {
            if( array[i][property] == key ) 
            {
                found = true;
                break;
            }
        }
        return found ? i : -1;
    };
})( jQuery );

Usage: $.find(items, "name", "xyz");

1 Comment

You would not put this function on $.fn

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.