Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: sorting two dimensional array with parseInt()

1. ## 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

• 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.

• A return a[1]-b[1];in the function is enough to work with integers

• 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.

•