Search

jQuery: Checking if an Item is an Array

October 25, 2014 —John Koster

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:

1 
2// First, the array.
3var mySimpleArray = ["apple", "juice"];
4 
5if (!$.inArray("apple", mySimpleArray) == -1) {
6 // Item is in the array.
7 console.log("Apple was in the array.");
8} else {
9 // Item is not in the array.
10 console.log("Apple was not in the array.");
11}

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

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.