Trouble with an Array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Saint48198
    New Member
    • Feb 2007
    • 6

    Trouble with an Array

    I'm having trouble with an array of data created using the 'getElementsByT agName' call. I'm trying to remove duplicates from the Array. code follows:


    Code:
    // creates a list of all keywords and the removes any dublicates and printes the results
    	getKeywords : function() {
    		
    		var keywords = articleHolder.getElementsByTagName('span');
    		var savedKeywords = [];
    		for (var i =0, allKeywords = keywords.length; i<allKeywords; i++) {
    			savedKeywords[i] = new Array(articleHolder.getElementsByTagName('span')[i].firstChild.nodeValue);
    		}
    		
    		if (allKeywords > 0) {
    			var para = document.createElement('p');
    			var strong = document.createElement('strong');
    			para.appendChild(strong).appendChild(document.createTextNode('Keywords: '));
    			
    			savedKeywords.sort();
    			for ( var n = 0, allSaved = savedKeywords.length; n <allSaved; n++) {
    				alert(savedKeywords[n]);
    				if (savedKeywords[n] == savedKeywords[n + 1]) {
    					
    					savedKeywords.splice(n,1);
    					
    				}
    				else {
    					para.appendChild(document.createTextNode(savedKeywords[n]));
    					para.appendChild(document.createTextNode(', '));
    				}
    			}
    			
    			
    		}
    				
    			articleHolder.insertBefore(para, document.getElementById('copyright'));
    	}
  • dorinbogdan
    Recognized Expert Contributor
    • Feb 2007
    • 839

    #2
    What kind of errors do you get?
    Do you have some code for articleHolder to provide too?

    Comment

    • Saint48198
      New Member
      • Feb 2007
      • 6

      #3
      I get no errors, but the code is not removing the duplicates from the Array. Intire code follows.

      Code:
      var pageOptions = {
      
      	articleHolder : null,
      	
      	// get the JS to starting doing its job
      	init : function() {
      		if (document.getElementById) {
      			articleHolder = document.getElementById('content'),  // the div holding the article;
      			pageOptions.addButtons();
      			pageOptions.getKeywords();
      		}
      	},
      	
      	// create the h3, form, p, input, and input text; append the latter three and add function to each of the buttons
      	addButtons : function() {
      		// create title for the section
      		var formTitle = document.createElement('h3');
      		formTitle.appendChild(document.createTextNode('Customize Article Display'));
      		
      		var buttonsForm = document.createElement('form');
      		buttonsForm.setAttribute('method','post');
      		buttonsForm.setAttribute('action','');
      		buttonsForm.setAttribute('id','buttons');
      		
      	
      		
      		// variable for each button for asigning value
      		var actionButtons = [];
      		
      		// create the p elements with input elements appened to each p element
      		for (var i = 0; i < 4; i++) {
      			var para = document.createElement('p');
      			actionButtons[i] = document.createElement('input');
      			actionButtons[i].setAttribute('type','button');
      			
      			buttonsForm.appendChild(para).appendChild(actionButtons[i]);
      		}
      		
      		// set deafult value for each button
      		actionButtons[0].setAttribute('value','Increase Line Spacing');
      		actionButtons[1].setAttribute('value','Highlight Keywords');
      		actionButtons[2].setAttribute('value','Highlight Text on Hover');
      		actionButtons[3].setAttribute('value','Hide Quotations');
      		
      		// get Element ID for the container and the h3 elements within the  container
      		var container = document.getElementById('rightcol');
      		var elementH3 = container.getElementsByTagName('h3');
      		
      		
      		
      		for (var n = 0; n <  elementH3.length; n++) {
      			
      			// insert the form after the firt non javScript h3 element
      			container.insertBefore(buttonsForm, elementH3[0]);
      		}
      		
      		// inserted the h3 title tag at the top of the container
      		container.insertBefore(formTitle, container.firstChild);
      		
      		
      		// add functions to each button
      		actionButtons[0].onclick = pageOptions.alterLineSpacing;
      	    actionButtons[1].onclick = pageOptions.highlightKeywords;
      	    actionButtons[2].onclick = pageOptions.highlightSelections;
      	    actionButtons[3].onclick = pageOptions.alterQuoteDisplay;
      		
      	},
      	
      	// modify the line spacing based on the input button value
      	alterLineSpacing : function() {
      		
      	    if (this.getAttribute('value') == 'Increase Line Spacing') {
      		   articleHolder.className = 'morelineheight';
      		   this.setAttribute('value','Decrease Line Spacing');     
      	    }
      	    else {
      		   articleHolder.className = '';
      		   this.setAttribute('value','Increase Line Spacing');
      	    }
      	},
      	
      	// modify keyword highlight based on the input button value
      	highlightKeywords : function() {
      	  
      	  var theKeywords = articleHolder.getElementsByTagName('span');
      	  var allKeywords = theKeywords.length;
      	  if (this.getAttribute('value') == 'Highlight Keywords') {
      		 for (var i=0; i<allKeywords; i++) {
      			 theKeywords[i].className = 'highlightword';      
      		 }
      		 this.setAttribute('value','No Keyword Highlights');   
      	  }
      	  else {
      		 for (var i=0; i<allKeywords; i++) {
      			 theKeywords[i].className = '';
      		 }    
      		 this.setAttribute('value','Highlight Keywords');
      	  }
      	},
      	
      	// modify text highlights based on the input button value
      	highlightSelections : function() {
      	  
      	  var paragraphs = articleHolder.getElementsByTagName('p');
      	  var allParas = paragraphs.length;
      	  if (this.getAttribute('value') == 'Highlight Text on Hover') {
      		 for (var i=0; i<allParas; i++) {
      			 paragraphs[i].onmouseover = function() {
      				this.className = 'highlightpara';
      			 }
      			 paragraphs[i].onmouseout = function() {
      				this.className = '';
      			 }
      		 }
      		 this.setAttribute('value','No Text Highlights');
      	  }
      	  else {
      		 for (var i=0; i<allParas; i++) {
      			 paragraphs[i].onmouseover = null;
      			 paragraphs[i].onmouseout = null;
      		 }    
      		 this.setAttribute('value','Highlight Text on Hover');
      	  }  
      	  
      	},
      	
      	// modify the display of quotations based on the input button value
      	alterQuoteDisplay : function() {
      	
      	  var blockquotes = articleHolder.getElementsByTagName('blockquote');
      	  for (var i=0, allBlockquotes = blockquotes.length; i<allBlockquotes; i++) {
      		  if (this.getAttribute('value') == 'Hide Quotations') {
      			  blockquotes[i].className = 'hide';
      		  this.setAttribute('value','Show Quotations');
      		  }
      		  else {
      			  blockquotes[i].className = '';
      			  this.setAttribute('value','Hide Quotations');
      		  }
      	  }
      	},
      	
      	// creates a list of all keywords and the removes any dublicates and printes the results
      	getKeywords : function() {
      		
      		var keywords = articleHolder.getElementsByTagName('span');
      		var savedKeywords = [];
      		for (var i =0, allKeywords = keywords.length; i<allKeywords; i++) {
      			savedKeywords[i] = new Array(articleHolder.getElementsByTagName('span')[i].firstChild.nodeValue);
      		}
      		
      		if (allKeywords > 0) {
      			var para = document.createElement('p');
      			var strong = document.createElement('strong');
      			para.appendChild(strong).appendChild(document.createTextNode('Keywords: '));
      			
      			savedKeywords.sort();
      			for ( var n = 0, allSaved = savedKeywords.length; n <allSaved; n++) {
      				alert(savedKeywords[n]);
      				if (savedKeywords[n] == savedKeywords[n + 1]) {
      					
      					savedKeywords.splice(n,1);
      					
      				}
      				else {
      					para.appendChild(document.createTextNode(savedKeywords[n]));
      					para.appendChild(document.createTextNode(', '));
      				}
      			}
      			
      			
      		}
      				
      			articleHolder.insertBefore(para, document.getElementById('copyright'));
      	},
      	
      	addEvent : function(obj, type, func) {
      		 if (obj.addEventListener) {obj.addEventListener(type, func, false);}
      		 else if (obj.attachEvent) {
      				obj["e" + type + func] = func;
      				obj[type + func] = function() {obj["e" + type + func] (window.event);}
      				obj.attachEvent("on" + type, obj[type + func]);
      		 }
      		 else {obj["on" + type] = func;}
      	  }
      }
      
      pageOptions.addEvent(window, 'load', pageOptions.init);

      Comment

      • dorinbogdan
        Recognized Expert Contributor
        • Feb 2007
        • 839

        #4
        I think that using savedKeywords.s plice(n,1) in the for loop is not appropriate because the array length and then element position are changed after each duplicate deletion.
        I'm looking further to find a workaround.

        Comment

        • Saint48198
          New Member
          • Feb 2007
          • 6

          #5
          Originally posted by dorinbogdan
          I think that using savedKeywords.s plice(n,1) in the for loop is not appropriate because the array length and then element position are changed after each duplicate deletion.
          I'm looking further to find a workaround.
          Ok, But should I not get an error. The code loops passed the if condition and does the else condition. I've tried using a temp variable to copy the array and then compare the two, but the condition for the if is never met. Thanks for any help.

          Comment

          • dorinbogdan
            Recognized Expert Contributor
            • Feb 2007
            • 839

            #6
            savedKeywords[i] = new Array(articleHo lder.getElement sByTagName('spa n')[i].firstChild.nod eValue);

            This statement assigns to the element at position i of savedKeywords array a new object of type Array, that is a pointer to a string.

            In this case, to compare the strings you can use:

            if (savedKeywords[n][0] == savedKeywords[n + 1][0])

            Comment

            • dorinbogdan
              Recognized Expert Contributor
              • Feb 2007
              • 839

              #7
              OR, remove "new Array" usage, and assign directly the value of the span:

              savedKeywords[i] = articleHolder.g etElementsByTag Name('span')[i].firstChild.nod eValue;

              Then, in order to remove duplicate elements you could create a new Array that is filled in the "else" section of the "for" loop, after checking if the last added value is different from the current one.

              Comment

              • Saint48198
                New Member
                • Feb 2007
                • 6

                #8
                Originally posted by dorinbogdan
                OR, remove "new Array" usage, and assign directly the value of the span:

                savedKeywords[i] = articleHolder.g etElementsByTag Name('span')[i].firstChild.nod eValue;

                Then, in order to remove duplicate elements you could create a new Array that is filled in the "else" section of the "for" loop, after checking if the last added value is different from the current one.
                I've removed new Array from the savedKeyword array, But I'm not clear about about creating the else for the for loop. Could you give me an example?

                Comment

                • dorinbogdan
                  Recognized Expert Contributor
                  • Feb 2007
                  • 839

                  #9
                  I mean the "else" section where apeears the line:
                  para.appendChil d(document.crea teTextNode(save dKeywords[n]));

                  See my changes bellow:

                  Code:
                  	savedKeywords.sort();
                  	var savedKeywordsNew = [];
                  	var lastValue = "";
                  	for ( var n = 0, allSaved = savedKeywords.length; n <allSaved; n++) {
                  		alert(savedKeywords[n]);
                  		if (savedKeywords[n] == savedKeywords[n + 1]) {
                  			//savedKeywords.splice(n,1);
                  			
                  		}
                  		else {
                  			If (lastValue != savedKeywords[n]){
                  				para.appendChild(document.createTextNode(savedKeywords[n]));
                  				para.appendChild(document.createTextNode(', '));
                  				savedKeywordsNew[savedKeywordsNew.length] = savedKeywords[n];
                  				lastValue = savedKeywords[n];
                  			}
                  		}
                  	}

                  Comment

                  • Saint48198
                    New Member
                    • Feb 2007
                    • 6

                    #10
                    Originally posted by dorinbogdan
                    I mean the "else" section where apeears the line:
                    para.appendChil d(document.crea teTextNode(save dKeywords[n]));

                    See my changes bellow:

                    Code:
                    	savedKeywords.sort();
                    	var savedKeywordsNew = [];
                    	var lastValue = "";
                    	for ( var n = 0, allSaved = savedKeywords.length; n <allSaved; n++) {
                    		alert(savedKeywords[n]);
                    		if (savedKeywords[n] == savedKeywords[n + 1]) {
                    			//savedKeywords.splice(n,1);
                    			
                    		}
                    		else {
                    			If (lastValue != savedKeywords[n]){
                    				para.appendChild(document.createTextNode(savedKeywords[n]));
                    				para.appendChild(document.createTextNode(', '));
                    				savedKeywordsNew[savedKeywordsNew.length] = savedKeywords[n];
                    				lastValue = savedKeywords[n];
                    			}
                    		}
                    	}
                    thanks, that did it.

                    Comment

                    • Saint48198
                      New Member
                      • Feb 2007
                      • 6

                      #11
                      One last question if you don't mind. How would you create a loop to remove duplicates without using sort?

                      Comment

                      • dorinbogdan
                        Recognized Expert Contributor
                        • Feb 2007
                        • 839

                        #12
                        Originally posted by Saint48198
                        One last question if you don't mind. How would you create a loop to remove duplicates without using sort?
                        I'm sure that exist methods without sort, but they would be more complex.
                        If you really need, I will research for that deeper.

                        Comment

                        • acoder
                          Recognized Expert MVP
                          • Nov 2006
                          • 16032

                          #13
                          Originally posted by Saint48198
                          One last question if you don't mind. How would you create a loop to remove duplicates without using sort?
                          Well, it should be possible, but it won't be as efficient. You can have two arrays. One contains the words, the second one is empty. Then as you loop through the first array, you call a function which checks in the second array (has the word already been added). If the word is already present it is ignored, otherwise it is added. It should be quite simple to implement.

                          Comment

                          • mrhoo
                            Contributor
                            • Jun 2006
                            • 428

                            #14
                            Code:
                            	Array.prototype.hasAny= function(wot){		
                            		var L= this.length, cnt= 0;
                            		for(var i= 0; i< L; i++){				
                            			if(A[i]=== wot) ++cnt;		
                            		}
                            		return cnt;
                            	}
                            	Array.prototype.unique= function(){
                            		var A= [];
                            		var L= this.length;
                            		for(var i= 0; i< L; i++){
                            			var tem= this[i];
                            			if(A.hasAny(tem)== 0) A.push(tem);
                            		}
                            		return A;
                            	}

                            Comment

                            Working...