Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove Duplicate Array 1

Status
Not open for further replies.

MarkZK

Technical User
Jul 13, 2006
202
GB
Hi all,

Could someone please tell me the best way to remove a duplicate string from an array, for example, if I have this script...

Code:
<html>
<body>
<script type="text/javascript">
var str="zz1,tr4,de6,q2q,tr4,qq0"
a=str.split(",")
for (i = 0; i <a.length; i++){
document.write(a[i]+"<br \/>")
}
</script>
</body>
</html>

the output is
Code:
zz1
tr4
de6
q2q
tr4
qq0

although, I'd like it to be ...

Code:
zz1
tr4
de6
q2q
qq0
removing "tr4" as it appears twice,

Thanks
 
I'd use a simple associative array (hashmap)... something like this:

Code:
<script type="text/javascript">
	var dupsArray = [];
	var str = 'zz1,tr4,de6,q2q,tr4,qq0';
	a = str.split(',');
	for (var loop=0; loop<a.length; loop++) {
		var theValue = a[loop]
		if (typeof(dupsArray[theValue] == 'undefined') {
			document.write(theValue + '<br \/>');	
		}
		dupsArray[theValue] = true;
	}
</script>

Hope this helps,
Dan

Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
This looks great, I prefer this to the results at google,

Thanks Billy Ray Preachers Son. :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top