JavaScript Remove Duplicate Values from Array String
Introduction
Here
I will explain how to use JavaScript to remove duplicate values from array or remove duplicate values/elements from string array using JavaScript.
Description:
In
previous article I explained JavaScript, jQuery,
SQL, asp.net
etc. Now I will explain how to remove duplicate values/elements from string
array using JavaScript.
To
remove duplicate values/elements from string array using JavaScript
we
need to write the code like as shown below
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Remove duplicates from an array using JavaScript </title>
<script type="text/javascript">
function RemoveList() {
var sampleArr = new Array(1,
1, 1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4); //Sample array
uniqueArr(sampleArr);
}
//Adds new uniqueArr values to
temp array
function uniqueArr(arr) {
arr1 = new
Array();
for (i = 0; i < arr.length; i++) {
if (!checkstatus(arr1, arr[i])) {
arr1.length += 1;
arr1[arr1.length - 1] = arr[i];
}
}
alert(arr1);
}
// Check if it contains unique or
duplicate record
function checkstatus(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="Remove Duplicates" onclick="RemoveList()"
/>
</div>
</body>
</html>
|
Live Demo
For
live demo click on below button it will return only unique values from this
string (1, 1, 1, 1, 1, 2, 2, 3, 3,
3, 4, 4, 4)
values
No comments:
Post a Comment