How to Find the Duplicate Value in Array using JavaScript

While working on an ASP.Net project, we often will get a scenario to check the duplicate input value like on the textbox value. We can do it like this.

the page at localhost

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"  
  2.     CodeFile="Default3.aspx.cs" Inherits="Default3" %>  
  3.    
  4. <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">  
  5.     <script type="text/javascript">  
  6.    
  7.     function testValues() {  
  8.         var no1 = document.getElementById('<%= TextBox1.ClientID %>').value;  
  9.         var no2 = document.getElementById('<%= TextBox2.ClientID %>').value;  
  10.         var no3 = document.getElementById('<%= TextBox3.ClientID %>').value;  
  11.         var no4 = document.getElementById('<%= TextBox4.ClientID %>').value;  
  12.         var arrInput = [no1,no2,no3,no4];  
  13.         var sorted_arr = arrInput.sort();   
  14.         var results = [];  
  15.         for (var i = 0; i < arrInput.length - 1; i++) {  
  16.             if (sorted_arr[i + 1] == sorted_arr[i]) {  
  17.                 results.push(sorted_arr[i]);  
  18.             }  
  19.         }  
  20.    
  21.         alert("duplicate Value:  " + results);  
  22.     }  
  23.    
  24.     </script>  
  25. </asp:Content>  
  26. <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">  
  27.     <asp:TextBox ID="TextBox1" runat="server" />  
  28.     <br />  
  29.     <asp:TextBox ID="TextBox2" runat="server" />  
  30.     <br />  
  31.     <asp:TextBox ID="TextBox3" runat="server" />  
  32.     <br />  
  33.     <asp:TextBox ID="TextBox4" runat="server" />  
  34.     <br />  
  35.     <br />  
  36.     <asp:Button ID="Button1" Text="Submit" OnClientClick="testValues();" runat="server" />  
  37. </asp:Content>  
Summary

I have seen so many developers write custom validation logic using C# in a code behind file. But that is not a good practice since it will degrade the performance of the application. We should write maximum code on the client side using JavaScript.

I hope it will be helpful while implementing the custom validation in a web based project on the client side.

 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now