Introduction
This article explains how to remove duplicate values from a single array list. A JavaScript Array is a global object and is the constructor for arrays. Arrays in JavaScript are zero-based; that means that JavaScript starts counting from 0 when it indexes an array. It means that the index value of the first element in the array is "0" and the index value of the second element is "1" and so on.
A JavaScript array is initialized with the given elements, except in the case where a single argument is passed to the Array constructor and that argument is a number. Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations.
Step 1
Open Visual Studio then select "File" -> "New" -> "Website ..." as in the following figure:
Step 2
Now go to Solution Explorer to the right side and add a new item in the web site as in the following figure:
Step 3
Now select a new web form as in the following figure:
Step 4
Now write the following code in the default.aspx page:
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title></title>
- <script type="text/javascript">
- function RemoveDuplValues() {
- var dupvaluearr = new Array(5,5,1,1,2,2,2,2,8,8,8,9,9);
- tempArr(dupvaluearr);
- }
- function tempArr(arr) {
- newArr = new Array();
- for (i = 0; i < arr.length; i++) {
- if (!duplValuescheck(newArr, arr[i])) {
- newArr.length += 1;
- newArr[newArr.length - 1] = arr[i];
- }
- }
- alert(newArr);
- }
- function duplValuescheck(arr, e) {
- for (j = 0; j < arr.length; j++) if (arr[j] == e) return true;
- return false;
- }
- </script>
- </head>
- <body>
- <div>
- <input type="button" value="Duplicate Values Removed" onclick="RemoveDuplValues()" />
- </div>
- </body>
- </html>
JavaScript arrays are zero-indexed, the first element of an array is at index 0, and the last element is at the index equal to the value of the array's "length" property minus (-1). The length property represents an unsigned, 32-bit integer that specifies the number of elements available in the array. The length property is one based because whenever we count the length of the array it starts from one until you reach the last element of the array.
Step 5
Now debug the application by pressing F5 then the output will appear as in the following figure:
Step 6
Now click on the button to remove the duplicate values from the array as in the following figure:
Summary
This article has shown how to remove duplicate values from an array in JavaScript. JavaScript arrays are zero-based. The JavaScript array length property returns the number of elements in the array.