www.webdeveloper.com
Results 1 to 11 of 11

Thread: Help with sorting a two dimensional array

  1. #1
    Join Date
    Dec 2010
    Posts
    4

    Question Help with sorting a two dimensional array

    Hi all, i am making a highscores table, i have this array:

    var myarray = [
    ["Raul","Corrales","$12000.00",1993],
    ["Arnold","Swarzenneger","$99000.00",1952],
    ["Sylvester","Stallone","$87000.00",1956]
    ];


    In other time i was use a function to sort this but i lost the code and forget it

    I want sort by name, or sort by lastname, or sort by money, or sort by birth year.

    Example Sorting by name:

    Arnold
    Raul
    Sylvester


    I hope you understand my bad english. Thanks all for read this and help. Greetings

  2. #2
    Join Date
    Jun 2004
    Location
    Portsmouth UK
    Posts
    2,689
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    </head>
    
    <body>
    <script type="text/javascript">
    /*<![CDATA[*/
    var myarray = [
    ["Raul","Corrales","$12000.00",1993],
    ["Arnold","Swarzenneger","$99000.00",1952],
    ["Sylvester","Stallone","$87000.00",1956]
    ];
    
    alert('Field 0\n'+myarray.sort(function(a,b){ return a[0]>b[0]?1:a[0]<b[0]?-1:0; }).join('\n'));
    alert('Field 1\n'+myarray.sort(function(a,b){ return a[1]>b[1]?1:a[1]<b[1]?-1:0; }).join('\n'));
    alert('Field 2\n'+myarray.sort(function(a,b){ return a[2]>b[2]?1:a[2]<b[2]?-1:0; }).join('\n'));
    alert('Field 3\n'+myarray.sort(function(a,b){ return a[3]>b[3]?1:a[3]<b[3]?-1:0; }).join('\n'));
    
    
    /*]]>*/
    </script>
    </body>
    
    </html>
    Vic

    God loves you and will never love you less.

    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

  3. #3
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,435

    Lightbulb

    Another attempt with more general application...
    Code:
    <!doctype html>
    <html>
    <head>
    <meta charset='utf-8'>
    <title> Multi-Dimension sort</title>
    </head>
    
    <script type="text/javascript">
    // From: http://codingforums.com/showthread.php?p=1012874#post1012874
    // Modified for: http://www.webdeveloper.com/forum/showthread.php?296111-Help-with-sorting-a-two-dimensional-array
    
    var data = [
     ['Smith','51','Wyoming',23],
     ['Rumsey','100','Florida',6],
     ['Brown', '68','Texas',20],
     ['Jones','28.99','Oregon',15],
     ['Smith','28.01','Oregon',15],
     ['Robinson', '83','Alabama',1]
    ];
    </script>
    
    <body>
    <div id="original"></div>
    <hr>
    <button onclick="document.getElementById('original').innerHTML = showArray()">Original</button>
    <button onclick="sortColumn(0);document.getElementById('results').innerHTML=showArray()">Names</button>
    <button onclick="sortColumn(1,false);document.getElementById('results').innerHTML=showArray()">Float</button>
    <button onclick="sortColumn(2,true);document.getElementById('results').innerHTML=showArray()">States</button>
    <button onclick="sortColumn(3,false);document.getElementById('results').innerHTML=showArray()">Integer</button>
    <hr>
    <div id="results"></div>
    
    <script type="text/javascript">
    function showArray() {
      var str = '';  
      for ( var i = 0; i < data.length; ++i ) { str += data[i].join(':') + '<br>'; }
      return str;
    }
    
    function sortColumn(fld,flag) {  
      if (flag == undefined) { flag = true; }  // default to non-numeric sort
      var str = '';  
      if (flag) {
        var sorted = data.sort ( function(s1,s2) { return s1[fld] > s2[fld]; } );
      } else {
        var sorted = data.sort ( function(s1,s2) { return parseFloat(s1[fld]) - parseFloat(s2[fld]); });
      }
    }
    
    onload = function () { document.getElementById('original').innerHTML = showArray(); }
    </script>
    
    </body>
    </html>
    Note, original display order is altered when other fields are sorted.

  4. #4
    Join Date
    Dec 2010
    Posts
    4
    thanks for the solutions, but i can not use this because i use unity.

    In unity3d in the function Sort() , i can not use more paremeters, if i want sort an array there i can use this:

    array.Sort();

    i am searching an other system to sort the array, is possible, but i dont know how do it..

    In the sort function i can not add nothing in the middle of the brackets.

    Greetings

  5. #5
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,502
    if its using JavaScript it will be array.sort() and not array.Sort()
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  6. #6
    Join Date
    Dec 2010
    Posts
    4
    unity have an self javascript code:

    http://docs.unity3d.com/ScriptReference/Array.Sort.html

  7. #7
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,502
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  8. #8
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,502
    Note that it says "Normal", if unity won't accept a function as a parameter then you need to raise this issue with Unity as a problem for them to amend.

    You might be better directing your query in the Unity forums.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  9. #9
    Join Date
    Mar 2009
    Posts
    521
    I don't know anything about Unity, but here is something that might help. It actually sorts arrays of objects by property but it can be used for your purposes as well.

    You use it as:

    objSort([array of arrays or objects],[numerical offset or property name],[optional--mode]);

    mode, if used, determines the type of sort. The default is alphabetical ascending. You
    can use: 'ad' --alphabetical descending, 'na' --numerical ascending, or 'nd' --numerical descending.

    It does not change the original array. It returns an array with the objects/arrays sorted as requested.

    The function:

    Code:
    function objSort(arr, prop, mode){
        var key, i, len, all, ret, val;
        key = {};
        all = [];
        ret = [];
        len = arr.length;
        for(i = 0; i < len; i++){
    	val = arr[i][prop];
    	if(!key[val]){
    	    key[val] = [];
    	    all.push(val);
    	}
    	key[val].push(arr[i]);
        }
        
        switch (mode){
        case "na":
    	all.sort(function(a, b){return a-b});
    	break;
        case "nd":
    	all.sort(function(a, b){return b-a});
    	break;
        case "ad":
    	all.sort();
    	all.reverse();
    	break;
        default:
    	all.sort();
        }
        
        len = all.length;
        for(i = 0; i < len; i++){
    	ret = ret.concat(key[all[i]]);
        }
        return ret;
    }
    Note also that it allows you to do "layered" sorts. Start out with the least significant field and do the most significant last.

    For example, lets say that you wish to have the following array sorted by last name, first name, and year of birth:

    Code:
    var k =[ ["John","Smith", 1975],
    	 ["Albert", "Smith", 1981],
    	 ["Betty", "Smith", 1969],
    	 ["Carl", "Adams", 1972],
    	 ["John","Smith", 1971],
    	 ["Adam","Doe", 1983]
    	 ];
    
    k = objSort(k, 2, 'na');  //sort by year of birth
    k = objSort(k ,0); //sort by first name
    k = objSort(k,1);  //sort by last name
    console.log(k);
    
    //this yields:
    [ [ 'Carl', 'Adams', 1972 ],
      [ 'Adam', 'Doe', 1983 ],
      [ 'Albert', 'Smith', 1981 ],
      [ 'Betty', 'Smith', 1969 ],
      [ 'John', 'Smith', 1971 ],
      [ 'John', 'Smith', 1975 ] ]

  10. #10
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,435

    Thumbs up

    Tcobb: Nice!

  11. #11
    @Tcobb -- your sort confuses me slightly; you seem to be making a LOT of 'variables for nothing'. I'd just use .slice() to make a copy at the start, and then index inside the sort.

    Code:
    function sCompare(a, b) {
    	if (a > b) return 1;
    	if (a < b) return -1;
    	return 0;
    }
    
    function uSort2d(arr, index, mode) {
    	arr = arr.slice();
    	switch(mode) {
    		case 'na':
    			return arr.sort(function(a, b) {
    				return Number(a[index]) - Number(b[index]);
    			});
    		case 'nd':
    			return arr.sort(function(a, b) {
    				return Number(b[index]) - Number(a[index]);
    			});
    		case 'id':
    			return arr.sort(function(a, b) {
    				return sCompare(
    					String(b[index]).toLowerCase(),
    					String(a[index]).toLowerCase()
    				);
    			});
    		case "d":
    			return arr.sort(function(a, b) {
    				return sCompare(String(b[index]), String(a[index]));
    			});
    		case 'ia':
    			return arr.sort(function(a, b) {
    				return sCompare(
    					String(a[index]).toLowerCase(),
    					String(b[index]).toLowerCase()
    				);
    			});
    		default:
    			return arr.sort(function(a, b) {
    				return sCompare(String(a[index]), String(b[index]));
    			});
    	}
    }
    "ia" and "id" would be case insensitive sorts. I force the typecasting for non-numeric sorts AND for the numeric just to make sure it sorts how we want 'em sorted.

    You know, a more robust approach might be to pass an array of indexes instead of just one -- that way you can state what field to fall back on when they are equal.
    Last edited by deathshadow; 06-09-2014 at 01:06 AM.

Thread Information

Users Browsing this Thread

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

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