469,277 Members | 2,276 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,277 developers. It's quick & easy.

duplicate data check from the array

hello,
I have the below code


Expand|Select|Wrap|Line Numbers
  1. <script language="javascript">
  2.     var myArray =new Array("tulu","dudu","tulu","milu")
  3.     for(i=0;i<myArray.length;i++)
  4.         {
  5.             alert(myArray[i])
  6.  
  7.         }
  8. </script> 
In the above code the alert message prints "tulu" twice. But I need to avoid duplicacy. Can anybody will help me to fix it.

Thanks in advance
Mar 30 '08 #1
3 2338
hsriat
1,654 Expert 1GB
Try this...
Expand|Select|Wrap|Line Numbers
  1. function arrayUnique(array) {
  2.     var p, i, j;
  3.     for(i = array.length; i;){
  4.         for(p = --i; p > 0;){
  5.             if(array[i] === array[--p]){
  6.                 for(j = p; --p && array[i] === array[p];);
  7.                 i -= array.splice(p + 1, j - p).length;
  8.             }
  9.         }
  10.     }
  11.     return true;
  12. }
Harpreet
Mar 30 '08 #2
thank you very much hsriat. Its working.
could you explain me the above code..
Mar 30 '08 #3
hsriat
1,654 Expert 1GB
Expand|Select|Wrap|Line Numbers
  1. function arrayUnique(array) {
  2.     var p, i, j;
  3.  
  4.     /*for each ith index in array
  5.     from the last index to the 0th*/
  6.     for(i = array.length; i;){
  7.  
  8.         /*for each pth,
  9.         moving from the ith to the 0th*/
  10.         for(p = --i; p > 0;){
  11.  
  12.             /*if ith is same as pth*/
  13.             if(array[i] === array[--p]){
  14.  
  15.                 /*going down the index,
  16.                 until same value exists*/
  17.                 for(j = p; --p && array[i] === array[p];);
  18.  
  19.                 /*remove the matching index/ices 
  20.                 update the value of i according
  21.                 to the latest length of the array*/
  22.                 i -= array.splice(p + 1, j - p).length;
  23.             }
  24.         }
  25.     }
  26.     return true;
  27. }
Regards
Mar 30 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by Eric Linders | last post: by
3 posts views Thread by Giloosh | last post: by
3 posts views Thread by shine | last post: by
2 posts views Thread by Trond | last post: by
2 posts views Thread by Egbert Teeselink | last post: by
7 posts views Thread by ucfcpegirl06 | last post: by
2 posts views Thread by Harry Haller | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.