0

I have the following array in javascript:

var myFirstArray = [1,2,3];

and i use $.inArrray() to see if a specific number is in that array like this

 var num =3;
 var exists = $.inArray(num, myFirstArray) > -1;

I now have an array of objects

var myArray = [{value:1, label:"bird"}, {value:2, label:"dog"}, {value:3, label: "cat"}];

if there anyway to use $.inArray() to search within a field of an object? Something like this:

var num = 3;
var exists = $.inArray(num, myFirstArray, (r) {return r.value}) > -1;

if the answer is NO, is there an alternative function that would give me this behavior that is performant?

1
  • 1
    No. See the documentation: inArray does not allow a predicate function. Commented Nov 23, 2013 at 20:27

2 Answers 2

2

Alternatively you can use one of the jQuery methods grep or each.

var num = 3;
var myArray = [{value: 1, label: "bird"}, {value:2, label:"dog"}, {value:3, label: "cat"}];

var result = jQuery.grep(myArray, function( element, index ) {
    return ( num === element.value );
});

var found = false;
$.each(myArray, function ( index, element ) {
    if ( num === element.value ) {
        found = true;
        return false;
   }
});
Sign up to request clarification or add additional context in comments.

Comments

2

You can use the native Array#some method:

var num =3;
var myArray = [{value:1, label:"bird"}, {value:2, label:"dog"}, {value:3, label: "cat"}];

var exists = myArray.some(function(o) {
    return o.value === num;
});

Live demo

If you need support for pesky IE<9: MDN Array.prototype.some shim or you may also use a complete ES5 shim already (thanks @user2864740). Underscore also provides the _.some utility.

1 Comment

@user2864740 Thanks, added the link to the answer. =]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.