duplicate data check from the array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dasrasmikant
    New Member
    • Jan 2008
    • 30

    duplicate data check from the array

    hello,
    I have the below code


    Code:
    <script language="javascript">
    	var myArray =new Array("tulu","dudu","tulu","milu")
    	for(i=0;i<myArray.length;i++)
    		{
    			alert(myArray[i])
    						
    		}
    </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
  • hsriat
    Recognized Expert Top Contributor
    • Jan 2008
    • 1653

    #2
    Try this...[code=javascript]function arrayUnique(arr ay) {
    var p, i, j;
    for(i = array.length; i;){
    for(p = --i; p > 0;){
    if(array[i] === array[--p]){
    for(j = p; --p && array[i] === array[p];);
    i -= array.splice(p + 1, j - p).length;
    }
    }
    }
    return true;
    }[/code]
    Harpreet

    Comment

    • dasrasmikant
      New Member
      • Jan 2008
      • 30

      #3
      thank you very much hsriat. Its working.
      could you explain me the above code..

      Comment

      • hsriat
        Recognized Expert Top Contributor
        • Jan 2008
        • 1653

        #4
        [code=javascript]function arrayUnique(arr ay) {
        var p, i, j;

        /*for each ith index in array
        from the last index to the 0th*/
        for(i = array.length; i;){

        /*for each pth,
        moving from the ith to the 0th*/
        for(p = --i; p > 0;){

        /*if ith is same as pth*/
        if(array[i] === array[--p]){

        /*going down the index,
        until same value exists*/
        for(j = p; --p && array[i] === array[p];);

        /*remove the matching index/ices
        update the value of i according
        to the latest length of the array*/
        i -= array.splice(p + 1, j - p).length;
        }
        }
        }
        return true;
        }[/code]

        Regards

        Comment

        Working...