Click here to Skip to main content
15,867,686 members
Articles / jQuery

Check Whether An Array Contains a Particular Element

Rate me:
Please Sign up or sign in to vote.
4.08/5 (7 votes)
30 Jun 2015CPOL2 min read 10.1K   7   1
In this article, we will see how we can check whether an array element is present in an array.

Introduction

In this article, we will see how we can check whether an array element is present in an array. We will be using jQuery for this requirement. I hope you will like it.

Background

I know we are all working in the client side technologies, especially in JQuery. Sometimes, we may need to write more client side code rather than server side code. In that case, you will be using client side arrays too. So if you use client side arrays, sometimes you may need to check whether the array contains a particular element or not. Then only, you can write some code according to that. Here, I am going to give you a demo of how we can do this.

Using the Code

To start with, as you all know, we need to load the JQuery reference.

JavaScript
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

Once you load the reference, you are ready to go.

Since this is a demo, we will explain with some steps. Sounds good? So we will do the following tasks:

  • Add the elements to the array
  • Check the elements are added or not
  • Search an element

Shall we start then?

Add the Elements to the Array

We need to set our UI first, right?

XML
<body>
    Check whether an array contains a particular element - Sibeesh Passion
    <br/>
    <br/>
    <table>
        <tr>
            <td>
                <input type="text" id="myText" />
            </td>
            <td>
                <p id="addMe">Add Me</p>
            </td>
        </tr>
        <tr></tr>
        <tr></tr>
        <tr></tr>
        <tr>
            <td>
                <p id="showMe">Show Array Length</p>
            </td>
            <td id="showContent">Array length is
            </td>
        </tr>
        <tr></tr>
        <tr></tr>
        <tr></tr>
        <tr>
            <td>
                <input type="text" id="searchText" />
            </td>
            <td>
                <p id="searchMe">Search Me</p>
            </td>
            <td id="searchOutput">The given text </td>
        </tr>
    </table>    
</body>

So we have set our UI, and now if you run your page, you can see output as follows:

www.sibeeshpassion.com

Now, we will add the required scripts.

JavaScript
<script>
        $(document).ready(function() {
            var myArray = [];
            var i = 0;
            $("#addMe").click(function() {
                myArray[i] = $("#myText").val();
                $("#myText").val('');
                i++;
            });
            $("#showMe").click(function() {
                $("#showContent").text("Array length is " + myArray.length);
            });
            $("#searchMe").click(function() {
                if (jQuery.inArray($("#searchText").val(), myArray) > -1)
                    $("#searchOutput").text("The given text " + $("#searchText").val() + 
                                            " is available in the array");
                else
                    $("#searchOutput").text("The given text " + $("#searchText").val() + 
                                            " is  not available in the array");

            });
        });
    </script>

As you can see, we are adding elements to the array, checking the array element in the first two click functions. But what about the third click function. Bingo! There we are using jQuery.inArray function to check our element is present in the array or not.

Now, we will learn a little about the jQuery.inArray function.

jQuery.inArray

  • It is used for searching a specified value within an array
  • It returns -1 if it does not contain the searched value
  • It returns index of the searched value if it contains the value

The following code block describes how we can use jQuery.inArray.

JavaScript
if (jQuery.inArray($("#searchText").val(), myArray) > -1)
                    $("#searchOutput").text("The given text " + $("#searchText").val() + 
                                            " is available in the array");
                else
                    $("#searchOutput").text("The given text " + $("#searchText").val() + 
                                            " is  not available in the array");

Complete Code

XML
<html>

<head>
    <title>Check whether an array contains a particular element - Sibeesh Passion</title>
    <style>
        p {
            color: red;
            width: 170px;
            cursor: pointer;
            border: 1px solid #ccc;
            text-align: center;
        }
    </style>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>

<body>
    Check whether an array contains a particular element - Sibeesh Passion
    <br/>
    <br/>
    <table>
        <tr>
            <td>
                <input type="text" id="myText" />
            </td>
            <td>
                <p id="addMe">Add Me</p>
            </td>
        </tr>
        <tr></tr>
        <tr></tr>
        <tr></tr>
        <tr>
            <td>
                <p id="showMe">Show Array Length</p>
            </td>
            <td id="showContent">Array length is
            </td>
        </tr>
        <tr></tr>
        <tr></tr>
        <tr></tr>
        <tr>
            <td>
                <input type="text" id="searchText" />
            </td>
            <td>
                <p id="searchMe">Search Me</p>
            </td>
            <td id="searchOutput">The given text </td>
        </tr>
    </table>
    <script>
        $(document).ready(function() {
            var myArray = [];
            var i = 0;
            $("#addMe").click(function() {
                myArray[i] = $("#myText").val();
                $("#myText").val('');
                i++;
            });
            $("#showMe").click(function() {
                $("#showContent").text("Array length is " + myArray.length);
            });
            $("#searchMe").click(function() {
                if (jQuery.inArray($("#searchText").val(), myArray) > -1)
                    $("#searchOutput").text("The given text " + $("#searchText").val() + 
                                            " is available in the array");
                else
                    $("#searchOutput").text("The given text " + $("#searchText").val() + 
                                            " is  not available in the array");

            });
        });
    </script>
</body>

</html>

Now we will run our page and see the output.

Output

www.sibeeshpassion.com

www.sibeeshpassion.com

www.sibeeshpassion.com

www.sibeeshpassion.com

That is all.

Conclusion

I hope you liked this article. Please share your valuable thoughts and comments. Your feedback is always welcome.

Thanks in advance. Happy coding!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Germany Germany
I am Sibeesh Venu, an engineer by profession and writer by passion. I’m neither an expert nor a guru. I have been awarded Microsoft MVP 3 times, C# Corner MVP 5 times, DZone MVB. I always love to learn new technologies, and I strongly believe that the one who stops learning is old.

My Blog: Sibeesh Passion
My Website: Sibeesh Venu

Comments and Discussions

 
QuestionThis can easily be done with plain JavaScript, no need for jQueery! Pin
Gerd Wagner1-Jul-15 2:26
professionalGerd Wagner1-Jul-15 2:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.