Sorting Multidimensional Array with Javascript: Integers

Posted by tkm256 on Stack Overflow See other posts from Stack Overflow or by tkm256
Published on 2011-02-08T21:54:46Z Indexed on 2011/02/08 23:25 UTC
Read the original article Hit count: 184

I have a 2D array called "results." Each "row" array in results contains both string and integer values. I'm using this script to sort the array by any "column" on an onclick event:

function sort_array(results, column, direction) {
var sorted_results = results.sort(value);
function value(a,b) {
    a = a[column];
    b = b[column];
    return a == b ? 0 : (a < b ? -1*direction : 1*direction)
    }
}

This works fine for the columns with strings. But it treats the columns of integers like strings instead of numbers. For example, the values 15, 1000, 200, 97 would be sorted 1000, 15, 200, 97 if "ascending" or 97, 200, 15, 1000 "descending."

I've double-checked the typeof the integer values, and the script knows they're numbers. How can I get it to treat them as such?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about sorting