473,326 Members | 2,114 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Trouble with an Array

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
13 1968
dorinbogdan
839 Expert 512MB
What kind of errors do you get?
Do you have some code for articleHolder to provide too?
Feb 19 '07 #2
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
839 Expert 512MB
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
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
839 Expert 512MB
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
839 Expert 512MB
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
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
839 Expert 512MB
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
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
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
839 Expert 512MB
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
16,027 Expert Mod 8TB
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
mrhoo
428 256MB
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

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

Similar topics

2
by: Alex Hopson | last post by:
Hi, I'm trying to modify a shopping cart script from Mastering PHP/MySQL and am having trouble setting up some arrays for it. The original code, below, stores the cart items in a session...
1
by: Andre Ranieri | last post by:
I'm having trouble programatically inserting an Excel file into an Image column in our CRM package's SQL 2000 database. The function appears to work ok, but when I attempt to access the file through...
4
by: DaHool | last post by:
Hi there !!! I browsed around the Internet in search for a solution of a little difficult problem i have in VB.NET.... However, i cannot find a suitable anwser anywhere, so i thought i'll give...
2
by: 4Ankit | last post by:
hey guys i am having trouble changing my array code to include a 'for/ in' structure the code i am trying to change is below: <script type="text/javascript"> var contents = new Array(3)
6
by: _Skare_Krow_ | last post by:
I have a database with three columns. One is an atomic number, one is a pic url, and the other is a description. What I'm having trouble doing is putting the url in one table row and the...
9
by: Nathan Sokalski | last post by:
I am trying to use the System.Array.ForEach method in VB.NET. The action that I want to perform on each of the Array values is: Private Function AddQuotes(ByVal value As String) As String Return...
0
by: bmerlover | last post by:
This code makes sense to me, I'm just having trouble trying to understand why it doesn't work correctly. This is a GUI APP. When the Play button is Clicked, the play_Click(System::Object * sender,...
0
by: jthep | last post by:
Hi, I'm trying to get user input for a record book but I'm having trouble as I think I'm not making the getline function read the buffer correctly. I have the following variables declared in...
3
by: Michellevt | last post by:
Hi I am working on a project (for college) and wondered if anyone can help me with my problem. In the project we are not allowed to make use of any "style" attributes but "class" attributes...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.