Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies


sorting a two dimensional array

3:16 pm on Dec 24, 2011 (gmt 0)

Junior Member

5+ Year Member

joined:Feb 7, 2010
posts: 119
votes: 0

I have a document that contains a number of abbr and acronym elements that I hope to 1collect, 2sort, 3eliminate duplicates and 4display in a definition list. I'm on 2sort and here's what I have so far:

//loop thru abbr and acronym elements
var mylen = mycoll.length;
var mynodes_titles = new Array();
for(var i=0; i<mylen; i++){
var curr_ele = mycoll[i];
//if the element content is empty loop back
if (curr_ele.lastChild.length < 1) continue;
var mynodevalue = mycoll[i].lastChild.nodeValue;
var mytitle = mycoll[i].getAttribute("title");

//debugging purposes
x = typeof(mynodevalue);
y = typeof(mytitle);

//create a one dimensional array
nodevalue_title = [mynodevalue,mytitle];
//create a two dimensional array
mynodes_titles[i] = nodevalue_title;
mynodes_titles = mynodes_titles.sort();

I thought I had my head around arrays as objects but I'm confused again. The code mynodes_titles.sort() actually sorts the array in alphabetical order and I did not expect it to? I assumed it would use the mynodes_titles numeric index? I'm pleased it did sort, I just do not understand the how. I was prepared for a hard row to hoe given all I've read about js sorting; but poof! It displayed in alpha order. How'd it do dat! Thanks all.
4:37 pm on Dec 24, 2011 (gmt 0)

Senior Member

WebmasterWorld Senior Member penders is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month

joined:July 3, 2006
posts: 3123
votes: 0

The Array.sort() method, without passing a sort function, will sort the array values alphabetically. It does not sort by the indices/keys - the array is already sorted by the numeric index - this is the order of the array. The array is sorted in-place, so you do not need to assign it back to the original array. The Array is reindexed numerically.

mynodes_titles array is sorted in-place...

Array values are temporarily converted (if necessary) to strings in order to perform the comparison. In your case, the array values are arrays themselves so these are converted to a comma-separated list eg. "nodevalue,mytitle" - so it will effectively be sorted by the nodevalue.
11:55 am on Dec 26, 2011 (gmt 0)

Junior Member

5+ Year Member

joined:Feb 7, 2010
posts: 119
votes: 0

Thanks penders, I should have known that; must of had PHP ksort cannibalizing my memory!

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members