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!

2
  • Guffa has your answer, you might like to read the relevant part of ECMA-262 and also what MDN says about sort. Note also that named function expressions are problematic in IE, far better to just use function declarations. Commented Jan 19, 2013 at 7:22
  • Indeed he covered the answer and shed light on my problem. Thanks for pointing me to some more technical reading about it. Commented Jan 19, 2013 at 7:40

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.