www.webdeveloper.com
Results 1 to 12 of 12

Thread: sorting multidimensional arrays

  1. #1
    Join Date
    Aug 2005
    Posts
    243

    sorting multidimensional arrays

    say i have a simple array...

    Code:
    var myArray = [ ['Bob',32], ['Mary',28], ['Alice',33], ... ];
    I want to be able to resort this array (ascending/descending) by both name (myArray[i][0]) and age (myArray[i][1]). What's the easiest approach without creating a new array? Or is there one? I know of the sort() method, but wasn't sure that that would work here?

  2. #2
    Join Date
    Feb 2006
    Posts
    2,927
    Code:
    myArray.sort(function(a,b){
      if(a[0]==b[0]) return a[1]-b[1];
      if(a[0]>b[0]) return 1;
      return -1;
    })

  3. #3
    Join Date
    May 2003
    Location
    Between Baltimore and DC
    Posts
    3,579
    I wrote up how to extend Array to do it here:

    http://radio.javaranch.com/pascarell...615124260.html

    It is the same idea as MrHoo has, but with a little more flexibility.

    Eric

  4. #4
    Join Date
    Aug 2005
    Posts
    243
    Thanks for responding guys. I'm trying to do a basic proof of concept and it's not working for me. I know i'm overlooking something simple, but i can't put my finger on it. Getting the generic error...

    Code:
    TypeError: Result of expression 'document.getElementById('message').innerHTML' [] is not a function.
    Here's my markup...

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    	<title>Arrays</title>
    	<script type="text/javascript">
    		/* <![CDATA[ */
    			Array.prototype.sortMulti = function(){
    				var
    					argsLen = arguments.length,
    					args = arguments;
    				function custSort(a,b){
    					for(var i=0; i<argsLen; i++){
    						var
    							col = args[i],
    							x = a[col],
    							y = b[col];
    						if(x===y)continue;
    						return x > y;
    					}
    					return 0;
    				}
    				return this.sort(custSort);
    			}
    
    			var myArray = [
    				['fred',23],
    				['andy',34],
    				['sandra',48],
    				['sid',54],
    				['ian',15]
    			];
    
    			function printIt(){
    				document.getElementById('message').innerHTML(
    					myArray.sortMulti(0)
    				)
        	}
    		/* ]]> */
    	</script>
    </head>
    
    <body onload="printIt()">
    
    	<div id="message"></div>
    	
    </body>
    
    </html>

  5. #5
    Join Date
    May 2003
    Location
    Between Baltimore and DC
    Posts
    3,579
    innerHTML is not a method

    Code:
    document.getElementById('message').innerHTML = myArray.sortMulti(0);
    Eric

  6. #6
    Join Date
    Aug 2005
    Posts
    243
    Thanks Eric...i feel like a real idiot for not seeing that one. :P Now it's loading correctly, however the sortMulti() function doesn't seem to be having any affect on my array...

  7. #7
    Join Date
    May 2003
    Location
    Between Baltimore and DC
    Posts
    3,579
    Looks fine to me
    Code:
    			function printIt(){
                                    
                                    var sorted = myArray.sortMulti(0);
    
    				var out = [];
                                    for(var i=0;i<sorted.length;i++){
                                        out.push(sorted[i].join("--"));
                                    }
    				document.getElementById('message').innerHTML = out.join("<br/>");
        	                }

    It does not change the original array.

    Eric

  8. #8
    Join Date
    Aug 2005
    Posts
    243
    Thanks for the updated code. It's working as you described it would in FireFox. For some reason it's not working in Safari. Is there a trick to make it more cross-browser?

  9. #9
    Join Date
    May 2003
    Location
    Between Baltimore and DC
    Posts
    3,579
    Some strange reason if I call it with a button click it works, but it is not working onload. Scratching my head on this one.

    Eric

  10. #10
    Join Date
    Aug 2005
    Posts
    243
    I made the following changes and it's working for me. However, I'm not really sure why?

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    	<title>Arrays</title>
    	<script type="text/javascript">
    		/* <![CDATA[ */
    			Array.prototype.sortMulti = function(){
    				var
    					argsLen = arguments.length,
    					args = arguments;
    				function custSort(a,b){
    					for(var i=0; i<argsLen; i++){
    						var
    							col = args[i],
    							x = a[col],
    							y = b[col];
    /*
    						if(x===y)continue;
    						return x > y;
    */
    						switch(true){
    							case x < y : return -1; break;
    							case x > y : return 1; break;
    							default : return 0;
    						}
    					}
    /* 					return 0; */
    				}
    				return this.sort(custSort);
    			}
    
    			var myArray = [
    				['fred',23],
    				['andy',34],
    				['sandra',48],
    				['sid',54],
    				['ian',15]
    			];
    
    			function printIt(){
    				var sorted = myArray.sortMulti(1);
    				
    				var out = [];
    				for(var i=0;i<sorted.length;i++){
    					out.push(sorted[i].join("--"));
    				}
    				document.getElementById('message').innerHTML = out.join("<br/>");
        	}
    		/* ]]> */
    	</script>
    </head>
    
    <body onload="printIt()">
    
    	<div id="message"></div>
    	
    </body>
    
    </html>

  11. #11
    Join Date
    May 2003
    Location
    Between Baltimore and DC
    Posts
    3,579
    Yeah, I will have to look at it more later, I see that it is working fine with onload if the column is one and not zero. major WTF moment here.

    Eric

  12. #12
    Join Date
    Aug 2005
    Posts
    243
    Thanks for all your help Eric (and mrhoo)! You saved me hours of beating my head on my desk

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles