Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Processing array data

Status
Not open for further replies.

CharlieLaw

Programmer
Joined
Oct 8, 2006
Messages
5
Location
GB
I currently have a list which I grab all of the links within it using document.getElementById(section).getElementsByTagName("a"). Every second link is a nested list element and I want to grab the top level list item and its sibling and place it in a left column, then take the next list item and its sibling and place it in the right column, this pattern would continue until their are no more list items.

<li><a href="#">Link 1</a>
<ul><li><a href="#">Link 1a</a></li></ul>
</li>
<li><a href="#">Link 2</a>
<ul><li><a href="#">Link 2a</a></li></ul>
</li>
<li><a href="#">Link 3</a>
<ul><li><a href="#">Link 3a</a></li></ul>
</li>

So using the above as an example the left column would read link1, link1a, link3, link3a and the right column would read link2, link2a.

I currently have it set up using a long and inflexible if statement
if (allLinks == allLinks[1] || allLinks == allLinks[2]
|| allLinks == allLinks[5] || allLinks == allLinks[6]
|| allLinks == allLinks[9] || allLinks == allLinks[10]
|| allLinks == allLinks[13] || allLinks == allLinks[14]) {
some code......
}

Is it possible to capture 1 & 2, 5 & 6, 7 & 8, 11 & 12 items from an array, Or have I approached this all wrong? The solution has to be flexible enough that it does not matter how many links are within the list which is why I dont like the current if condition as potentially I would have to alter this when a large number of links were grabbed.

Cheers
Charlie.
 
Why not check for i instead of the contents of the array?

Code:
switch (i)
  {
  case 1:
  case 2:
  case 5:
  case 6:
  case 9:
  case 10:
  case 13:
  case 14:
    {
    //do something here
    break;
    }
  }

Lee
 
This will split the "allLinks" array into two arrays: "left" and "right" using the splice method.
Code:
var left = allLinks;
var right = [];
for(var i=left.length-2; i>=0; i=i-4){
  right.splice(0,0,left.splice(i,2));
}

Adam
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top