jQuery: Checking if an Item is an Array

JavaScript

When writing JavaScript, I am usually using the jQuery library. I also seem to work with arrays a lot. Most of the time I only care if an item is an existing array or not. That's pretty simple to do with jQuery, and looks like this:


// First, the array. var mySimpleArray = ["apple", "juice"]; if (!$.inArray("apple", mySimpleArray) == -1) { // Item is in the array. console.log("Apple was in the array."); } else { // Item is not in the array. console.log("Apple was not in the array."); }

The takeaway here is that when we use the $.inArray function, we check it's value against -1. -1 indicates that the item was not in the array.

Join the Discussion

Leave a comment

  • Mark
    Mark
    December 30, 2014 7:19 AM Reply

    ...or just: if mySimpleArray.indexOf("apple") == -1 { // Item is not in the array. console.log("Apple wasn't in the array."); } else { // Item is in the array. console.log("Apple was in the array."); }

    Or am I missing something?

    John
    John
    December 31, 2014 11:12 PM Reply

    Hello Mark,

    Using if (mySimpleArray.indexOf("apple") == -1) definitely works, and is the preferred way as it is much faster than iterating over the array yourself. If I'm not mistaken, starting with jQuery version 2, jQuery internally calls the native indexOf() method. With that said, some older browsers do not natively support the indexOf() method in their array implementations, so you would have to resort to traversing the array to check if the item exists. jQuery 1.x actually does this check, and will loop through the array if the indexOf() method isn't supported.

Subscribe to our newsletter