How to find the duplicate value in array using Javascript ?


Hi

While working on asp.net project, So many time we will get scenario to check the duplicate input value like on textbox value. We can do like this.


<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
    <script type="text/javascript">

    function testValues() {
        var no1 = document.getElementById('<%= TextBox1.ClientID %>').value;
        var no2 = document.getElementById('<%= TextBox2.ClientID %>').value;
        var no3 = document.getElementById('<%= TextBox3.ClientID %>').value;
        var no4 = document.getElementById('<%= TextBox4.ClientID %>').value;
        var arrInput = [no1,no2,no3,no4];
        var sorted_arr = arrInput.sort(); 
        var results = [];
        for (var i = 0; i < arrInput.length - 1; i++) {
            if (sorted_arr[i + 1] == sorted_arr[i]) {
                results.push(sorted_arr[i]);
            }
        }

        alert("duplicate Value:  " + results);
    }

    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
    <asp:TextBox ID="TextBox1" runat="server" />
    <br />
    <asp:TextBox ID="TextBox2" runat="server" />
    <br />
    <asp:TextBox ID="TextBox3" runat="server" />
    <br />
    <asp:TextBox ID="TextBox4" runat="server" />
    <br />
    <br />
    <asp:Button ID="Button1" Text="Submit" OnClientClick="testValues();" runat="server" />
</asp:Content>


Advertisements

5 Responses to “How to find the duplicate value in array using Javascript ?”

  1. Sumith Says:

    Hi Chandra,
    If the 1nd and 4th values are duplicate values, will this function work?

  2. Sumith Says:

    Sumith :
    Hi Chandra,
    eg: If the 1nd and 4th values are duplicate values, will this function work?

    • Chandra Dev Says:

      Yes. It will work.

      • Safia Says:

        Hey Chandra,

        I have a text box , it is for the servers to be entered for example test1 , tes1 , test 2 it should give a message saying server test1 is duplicate , how to do that ?

        Thank

  3. Chandra Dev Says:

    Hi
    Please check the above code. it will work.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: