473,799 Members | 2,734 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trouble with an Array

6 New Member
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:


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 1999
dorinbogdan
839 Recognized Expert Contributor
What kind of errors do you get?
Do you have some code for articleHolder to provide too?
Feb 19 '07 #2
Saint48198
6 New Member
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 Recognized Expert Contributor
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.
Feb 19 '07 #4
Saint48198
6 New Member
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.
Feb 19 '07 #5
dorinbogdan
839 Recognized Expert Contributor
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])
Feb 19 '07 #6
dorinbogdan
839 Recognized Expert Contributor
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.
Feb 19 '07 #7
Saint48198
6 New Member
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?
Feb 19 '07 #8
dorinbogdan
839 Recognized Expert Contributor
I mean the "else" section where apeears the line:
para.appendChil d(document.crea teTextNode(save dKeywords[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
Saint48198
6 New Member
I mean the "else" section where apeears the line:
para.appendChil d(document.crea teTextNode(save dKeywords[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

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

Similar topics

2
1841
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 variable array ($HTTP_SESSION_VARS = array();) basically this stores an associative array with the id number of the product and the qty (ie cart = qty of that product). This works fine, but I need to be able to have sub options AND colours for
1
13299
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 the application's front end the file appears to be corrupt. The front-end application has a way of inserting files to the column, however when I analyze this in SQL Profiler the contents of the Byte array appear to be quite different than the one...
4
4030
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 it a try here... Okay, here's the deal: I am trying to read from unmanaged memory with a class type struct, this
2
1453
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
1447
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 description in another table row right below it like this... <tr<tdsome pic url</td<tdother pic url</td></tr> <tr><tdsome descripts </td<tdother descript </td></tr> whilest limiting the rows to about 10 cells each,,.... any ideas?
9
5619
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 String.Format("'{0}'", value) End Function Basically, I just want to surround each value with single quotes. However, I am having trouble getting this to work using the System.Array.ForEach method. This may be partially because I am not very...
0
919
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, System::EventArgs * e) function is called, it is suppose to make the Play button dissapear and the Pause Button Appear as soon as the Play button is clicked. I don't know why it calls the keystrokes function then goes through the while loop...
0
1157
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 main: char name, address, telno, input; int yearofbirth, choice, records; yearofbirth = 0; choice = -1; Then here's part of the code where it goes wrong:
3
1924
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 instead. The following is the java script that i am using and i am having trouble in using a class instead of a style tag because simply replacing the style=\"position:absolute;\" tag with class=\"posiAbs\" where in the external css ".posiAbs...
0
10488
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10237
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9077
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7567
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6808
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5467
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4144
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.