Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Sep 2010
    Posts
    20
    Thanks
    3
    Thanked 1 Time in 1 Post

    sorting two dimensional array with parseInt()

    hi
    i have to sort a two dimensional array for google visualization api.
    the unsorted data works fine.
    structure of the unsorted array is:
    Code:
    [['stringA0',intB0],
    ['stringA1',intB1],
    ['stringA2'; intB2],
    ['stringA3'; intB3],
    ['stringA4'; intB4],
    ['stringA5'; intB5]]
    i have to sort on the second element. as demonstrated above, first element is a string, second an integer, and this should remain so.

    i use this function for sorting
    Code:
    myarray.sort(sortMultiDimensional);
    function sortMultiDimensional(a,b)
    {
        // this sorts the array using the second element    
        return ((a[1] < b[1]) ? -1 : ((a[1] > b[1]) ? 1 : 0));
    }
    but this turns the second element into a string. i didnt write the function (and i dont get it). where would i have to place parceInt() to make it work?

    cheers

  • #2
    New Coder
    Join Date
    Sep 2010
    Posts
    20
    Thanks
    3
    Thanked 1 Time in 1 Post
    i changed the function to
    Code:
    function sortMultiDimensional(a,b)
    {
    //make sure element stays an integer
    	a[1] = parseInt(a[1]);
    	b[1] = parseInt(b[1]);
    	// this sorts the array using the second element    
    	return ((a[1] < b[1]) ? -1 : ((a[1] > b[1]) ? 1 : 0));
    }
    and now things seem to be working.

  • #3
    Regular Coder
    Join Date
    May 2012
    Location
    France
    Posts
    216
    Thanks
    0
    Thanked 29 Times in 27 Posts
    A return a[1]-b[1];in the function is enough to work with integers

  • #4
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,458
    Thanks
    0
    Thanked 632 Times in 622 Posts
    What number base are the numbers in that you are converting to decimal using parseInt() - if they are already base 10 then you don't need to convert them and so don't need parseInt()

    To convert a string to a number you can
    1. wrap it inside Number( )
    2. wrap it inside (+ )
    3. subtract something from it
    4, multiply it by something
    5. divide something into it

    As you need to do the subtraction anyway that will take care of the conversion.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.


  •  

    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
    •