By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,663 Members | 1,273 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,663 IT Pros & Developers. It's quick & easy.

Trouble with an Array

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


Expand|Select|Wrap|Line Numbers
  1. // creates a list of all keywords and the removes any dublicates and printes the results
  2.     getKeywords : function() {
  3.  
  4.         var keywords = articleHolder.getElementsByTagName('span');
  5.         var savedKeywords = [];
  6.         for (var i =0, allKeywords = keywords.length; i<allKeywords; i++) {
  7.             savedKeywords[i] = new Array(articleHolder.getElementsByTagName('span')[i].firstChild.nodeValue);
  8.         }
  9.  
  10.         if (allKeywords > 0) {
  11.             var para = document.createElement('p');
  12.             var strong = document.createElement('strong');
  13.             para.appendChild(strong).appendChild(document.createTextNode('Keywords: '));
  14.  
  15.             savedKeywords.sort();
  16.             for ( var n = 0, allSaved = savedKeywords.length; n <allSaved; n++) {
  17.                 alert(savedKeywords[n]);
  18.                 if (savedKeywords[n] == savedKeywords[n + 1]) {
  19.  
  20.                     savedKeywords.splice(n,1);
  21.  
  22.                 }
  23.                 else {
  24.                     para.appendChild(document.createTextNode(savedKeywords[n]));
  25.                     para.appendChild(document.createTextNode(', '));
  26.                 }
  27.             }
  28.  
  29.  
  30.         }
  31.  
  32.             articleHolder.insertBefore(para, document.getElementById('copyright'));
  33.     }
Feb 19 '07 #1
Share this Question
Share on Google+
13 Replies

dorinbogdan
Expert 100+
P: 839
What kind of errors do you get?
Do you have some code for articleHolder to provide too?
Feb 19 '07 #2

P: 6
I get no errors, but the code is not removing the duplicates from the Array. Intire code follows.

Expand|Select|Wrap|Line Numbers
  1. var pageOptions = {
  2.  
  3.     articleHolder : null,
  4.  
  5.     // get the JS to starting doing its job
  6.     init : function() {
  7.         if (document.getElementById) {
  8.             articleHolder = document.getElementById('content'),  // the div holding the article;
  9.             pageOptions.addButtons();
  10.             pageOptions.getKeywords();
  11.         }
  12.     },
  13.  
  14.     // create the h3, form, p, input, and input text; append the latter three and add function to each of the buttons
  15.     addButtons : function() {
  16.         // create title for the section
  17.         var formTitle = document.createElement('h3');
  18.         formTitle.appendChild(document.createTextNode('Customize Article Display'));
  19.  
  20.         var buttonsForm = document.createElement('form');
  21.         buttonsForm.setAttribute('method','post');
  22.         buttonsForm.setAttribute('action','');
  23.         buttonsForm.setAttribute('id','buttons');
  24.  
  25.  
  26.  
  27.         // variable for each button for asigning value
  28.         var actionButtons = [];
  29.  
  30.         // create the p elements with input elements appened to each p element
  31.         for (var i = 0; i < 4; i++) {
  32.             var para = document.createElement('p');
  33.             actionButtons[i] = document.createElement('input');
  34.             actionButtons[i].setAttribute('type','button');
  35.  
  36.             buttonsForm.appendChild(para).appendChild(actionButtons[i]);
  37.         }
  38.  
  39.         // set deafult value for each button
  40.         actionButtons[0].setAttribute('value','Increase Line Spacing');
  41.         actionButtons[1].setAttribute('value','Highlight Keywords');
  42.         actionButtons[2].setAttribute('value','Highlight Text on Hover');
  43.         actionButtons[3].setAttribute('value','Hide Quotations');
  44.  
  45.         // get Element ID for the container and the h3 elements within the  container
  46.         var container = document.getElementById('rightcol');
  47.         var elementH3 = container.getElementsByTagName('h3');
  48.  
  49.  
  50.  
  51.         for (var n = 0; n <  elementH3.length; n++) {
  52.  
  53.             // insert the form after the firt non javScript h3 element
  54.             container.insertBefore(buttonsForm, elementH3[0]);
  55.         }
  56.  
  57.         // inserted the h3 title tag at the top of the container
  58.         container.insertBefore(formTitle, container.firstChild);
  59.  
  60.  
  61.         // add functions to each button
  62.         actionButtons[0].onclick = pageOptions.alterLineSpacing;
  63.         actionButtons[1].onclick = pageOptions.highlightKeywords;
  64.         actionButtons[2].onclick = pageOptions.highlightSelections;
  65.         actionButtons[3].onclick = pageOptions.alterQuoteDisplay;
  66.  
  67.     },
  68.  
  69.     // modify the line spacing based on the input button value
  70.     alterLineSpacing : function() {
  71.  
  72.         if (this.getAttribute('value') == 'Increase Line Spacing') {
  73.            articleHolder.className = 'morelineheight';
  74.            this.setAttribute('value','Decrease Line Spacing');     
  75.         }
  76.         else {
  77.            articleHolder.className = '';
  78.            this.setAttribute('value','Increase Line Spacing');
  79.         }
  80.     },
  81.  
  82.     // modify keyword highlight based on the input button value
  83.     highlightKeywords : function() {
  84.  
  85.       var theKeywords = articleHolder.getElementsByTagName('span');
  86.       var allKeywords = theKeywords.length;
  87.       if (this.getAttribute('value') == 'Highlight Keywords') {
  88.          for (var i=0; i<allKeywords; i++) {
  89.              theKeywords[i].className = 'highlightword';      
  90.          }
  91.          this.setAttribute('value','No Keyword Highlights');   
  92.       }
  93.       else {
  94.          for (var i=0; i<allKeywords; i++) {
  95.              theKeywords[i].className = '';
  96.          }    
  97.          this.setAttribute('value','Highlight Keywords');
  98.       }
  99.     },
  100.  
  101.     // modify text highlights based on the input button value
  102.     highlightSelections : function() {
  103.  
  104.       var paragraphs = articleHolder.getElementsByTagName('p');
  105.       var allParas = paragraphs.length;
  106.       if (this.getAttribute('value') == 'Highlight Text on Hover') {
  107.          for (var i=0; i<allParas; i++) {
  108.              paragraphs[i].onmouseover = function() {
  109.                 this.className = 'highlightpara';
  110.              }
  111.              paragraphs[i].onmouseout = function() {
  112.                 this.className = '';
  113.              }
  114.          }
  115.          this.setAttribute('value','No Text Highlights');
  116.       }
  117.       else {
  118.          for (var i=0; i<allParas; i++) {
  119.              paragraphs[i].onmouseover = null;
  120.              paragraphs[i].onmouseout = null;
  121.          }    
  122.          this.setAttribute('value','Highlight Text on Hover');
  123.       }  
  124.  
  125.     },
  126.  
  127.     // modify the display of quotations based on the input button value
  128.     alterQuoteDisplay : function() {
  129.  
  130.       var blockquotes = articleHolder.getElementsByTagName('blockquote');
  131.       for (var i=0, allBlockquotes = blockquotes.length; i<allBlockquotes; i++) {
  132.           if (this.getAttribute('value') == 'Hide Quotations') {
  133.               blockquotes[i].className = 'hide';
  134.           this.setAttribute('value','Show Quotations');
  135.           }
  136.           else {
  137.               blockquotes[i].className = '';
  138.               this.setAttribute('value','Hide Quotations');
  139.           }
  140.       }
  141.     },
  142.  
  143.     // creates a list of all keywords and the removes any dublicates and printes the results
  144.     getKeywords : function() {
  145.  
  146.         var keywords = articleHolder.getElementsByTagName('span');
  147.         var savedKeywords = [];
  148.         for (var i =0, allKeywords = keywords.length; i<allKeywords; i++) {
  149.             savedKeywords[i] = new Array(articleHolder.getElementsByTagName('span')[i].firstChild.nodeValue);
  150.         }
  151.  
  152.         if (allKeywords > 0) {
  153.             var para = document.createElement('p');
  154.             var strong = document.createElement('strong');
  155.             para.appendChild(strong).appendChild(document.createTextNode('Keywords: '));
  156.  
  157.             savedKeywords.sort();
  158.             for ( var n = 0, allSaved = savedKeywords.length; n <allSaved; n++) {
  159.                 alert(savedKeywords[n]);
  160.                 if (savedKeywords[n] == savedKeywords[n + 1]) {
  161.  
  162.                     savedKeywords.splice(n,1);
  163.  
  164.                 }
  165.                 else {
  166.                     para.appendChild(document.createTextNode(savedKeywords[n]));
  167.                     para.appendChild(document.createTextNode(', '));
  168.                 }
  169.             }
  170.  
  171.  
  172.         }
  173.  
  174.             articleHolder.insertBefore(para, document.getElementById('copyright'));
  175.     },
  176.  
  177.     addEvent : function(obj, type, func) {
  178.          if (obj.addEventListener) {obj.addEventListener(type, func, false);}
  179.          else if (obj.attachEvent) {
  180.                 obj["e" + type + func] = func;
  181.                 obj[type + func] = function() {obj["e" + type + func] (window.event);}
  182.                 obj.attachEvent("on" + type, obj[type + func]);
  183.          }
  184.          else {obj["on" + type] = func;}
  185.       }
  186. }
  187.  
  188. pageOptions.addEvent(window, 'load', pageOptions.init);
Feb 19 '07 #3

dorinbogdan
Expert 100+
P: 839
I think that using savedKeywords.splice(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.
Feb 19 '07 #4

P: 6
I think that using savedKeywords.splice(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.
Feb 19 '07 #5

dorinbogdan
Expert 100+
P: 839
savedKeywords[i] = new Array(articleHolder.getElementsByTagName('span')[i].firstChild.nodeValue);

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])
Feb 19 '07 #6

dorinbogdan
Expert 100+
P: 839
OR, remove "new Array" usage, and assign directly the value of the span:

savedKeywords[i] = articleHolder.getElementsByTagName('span')[i].firstChild.nodeValue;

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.
Feb 19 '07 #7

P: 6
OR, remove "new Array" usage, and assign directly the value of the span:

savedKeywords[i] = articleHolder.getElementsByTagName('span')[i].firstChild.nodeValue;

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?
Feb 19 '07 #8

dorinbogdan
Expert 100+
P: 839
I mean the "else" section where apeears the line:
para.appendChild(document.createTextNode(savedKeyw ords[n]));

See my changes bellow:

Expand|Select|Wrap|Line Numbers
  1.     savedKeywords.sort();
  2.     var savedKeywordsNew = [];
  3.     var lastValue = "";
  4.     for ( var n = 0, allSaved = savedKeywords.length; n <allSaved; n++) {
  5.         alert(savedKeywords[n]);
  6.         if (savedKeywords[n] == savedKeywords[n + 1]) {
  7.             //savedKeywords.splice(n,1);
  8.  
  9.         }
  10.         else {
  11.             If (lastValue != savedKeywords[n]){
  12.                 para.appendChild(document.createTextNode(savedKeywords[n]));
  13.                 para.appendChild(document.createTextNode(', '));
  14.                 savedKeywordsNew[savedKeywordsNew.length] = savedKeywords[n];
  15.                 lastValue = savedKeywords[n];
  16.             }
  17.         }
  18.     }
  19.  
  20.  
Feb 19 '07 #9

P: 6
I mean the "else" section where apeears the line:
para.appendChild(document.createTextNode(savedKeyw ords[n]));

See my changes bellow:

Expand|Select|Wrap|Line Numbers
  1.     savedKeywords.sort();
  2.     var savedKeywordsNew = [];
  3.     var lastValue = "";
  4.     for ( var n = 0, allSaved = savedKeywords.length; n <allSaved; n++) {
  5.         alert(savedKeywords[n]);
  6.         if (savedKeywords[n] == savedKeywords[n + 1]) {
  7.             //savedKeywords.splice(n,1);
  8.  
  9.         }
  10.         else {
  11.             If (lastValue != savedKeywords[n]){
  12.                 para.appendChild(document.createTextNode(savedKeywords[n]));
  13.                 para.appendChild(document.createTextNode(', '));
  14.                 savedKeywordsNew[savedKeywordsNew.length] = savedKeywords[n];
  15.                 lastValue = savedKeywords[n];
  16.             }
  17.         }
  18.     }
  19.  
  20.  
thanks, that did it.
Feb 19 '07 #10

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

dorinbogdan
Expert 100+
P: 839
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.
Feb 20 '07 #12

acoder
Expert Mod 15k+
P: 16,027
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.
Feb 20 '07 #13

100+
P: 428
Expand|Select|Wrap|Line Numbers
  1.     Array.prototype.hasAny= function(wot){        
  2.         var L= this.length, cnt= 0;
  3.         for(var i= 0; i< L; i++){                
  4.             if(A[i]=== wot) ++cnt;        
  5.         }
  6.         return cnt;
  7.     }
  8.     Array.prototype.unique= function(){
  9.         var A= [];
  10.         var L= this.length;
  11.         for(var i= 0; i< L; i++){
  12.             var tem= this[i];
  13.             if(A.hasAny(tem)== 0) A.push(tem);
  14.         }
  15.         return A;
  16.     }
Feb 21 '07 #14

Post your reply

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