0

I have a function for sorting a multi-dimensional array using JavaScript. It's working perfectly in both Firefox and Google Chrome, but not at all in IE. Is there some coding standard I'm not adhering to for cross browser compatibility?

function sortArray(arr, column, order) {

var asc = function sortAsc(a, b) {
    return (a[column] > b[column]);
}

var desc = function sortDesc(a, b) {
    return (a[column] < b[column]);
}

if (order=="desc")
{
    return arr.sort(desc);
}

return arr.sort(asc);
}

An example of a call would be: "sortArray(employees, 'name', 'desc')"

Any thoughts on what might fix this in IE so that it doesn't keep returning the original array would be helpful. Any ideas? Thanks!

Joshua
  • 1,260
  • 3
  • 17
  • 33
  • Guffa has your answer, you might like to read the relevant part of [ECMA-262](http://ecma-international.org/ecma-262/5.1/#sec-15.4.4.11) and also what [MDN says about `sort`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort). Note also that [named function expressions are problematic in IE](http://kangax.github.com/nfe/), far better to just use function declarations. – RobG Jan 19 '13 at 07:22
  • Indeed he covered the answer and shed light on my problem. Thanks for pointing me to some more technical reading about it. – Joshua Jan 19 '13 at 07:40

1 Answers1

1

You are taking advantage of a non-standard way of implementing the comparison, so it only works in some browsers.

The comparison should return zero if the items are equal, and a positive or negative value when they are not:

function asc(a, b) {
  return (a[column] == b[column] ? 0 : a[column] < b[column] ? -1 : 1);
}

function desc(a, b) {
  return asc(b, a);
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005