0

I am trying to write some code that will check to see if a group of numbers stored in an array exist in an object. With the code I have now it is always returning -1.

function checkHorizonal() {
    var x= ['1', '2' ,'3'];
    var y= ['4', '5', '6'];
    var z= ['7', '8', '9']


        console.log(jQuery.inArray(x, squaresClicked));

}

This is the squaresClicked object contents:

Object {1: "1", 2: "-1", 3: "1"}

You can see that the keys 1,2,3 exist but it will return -1.

2 Answers 2

1

From the jQuery doc:

jQuery.inArray( value, array [, fromIndex ] )

jQuery.inArray won't work the way you're using it. It checks for array contents, not object keys. Your value x is fine, but you're passing in an object instead of an array.

If you're trying to see if a set of integers exists as keys in an object, you can try the following (assuming you're using JavaScript >= 1.6):

myArray.filter(function(x) {
  // check if value is a key
  return (x in squaresClicked);
}).length == myArray.length;

Basically, we iterate through our array and return only those that exist as keys in the object squaresClicked. If the new array has the same length as our original list, then the values must all exist as properties in the object.

If you don't want to look up an objects entire prototype chain for the array value, you'll need to use hasOwnProperty instead of in.

Like so:

return (squaresClicked.hasOwnProperty(x));

You can read more about this method here.

Sign up to request clarification or add additional context in comments.

2 Comments

how do I output the matched integers to the console
store the boolean result in a variable. For example: var res = (x in squaresClicked). Then console.log(x) if it's true.
1

jQuery's inArray can't deal with an array of needles, otherwise

$.inArray(x, Object.keys(squaresClicked));

would've worked. In this case you are stuck with iterating, I guess (though there might be some other tricky way – as always). One way in jQuery (though I don't very much like it for various reasons1):

var hasFailed = false;
$.each(x, function (index, value) {
    if($.inArray(value, Object.keys(squaresClicked)) === -1) {
        hasFailed = true;
    }
});

return !hasFailed;

A basic vanillaJS approach:

for(var i = 0; i < x.length; i++) {
    if(!squaresClicked.hasOwnProperty(x[i])) {
        return false;
    }
}

return true;

1 Two of the reasons why I dislike it:

  • It will iterate over the entire array, even if it's already clear that it will fail
  • It uses a double negation in its logic

Comments

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.