View Full Version : sorting two dimensional array with parseInt()

11-29-2012, 10:04 AM
i have to sort a two dimensional array for google visualization api.
the unsorted data works fine.
structure of the unsorted array is:

['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

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?


11-29-2012, 11:13 AM
i changed the function to

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.

11-29-2012, 06:46 PM
A return a[1]-b[1];in the function is enough to work with integers

11-29-2012, 07:38 PM
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.