views:

79

answers:

3

When calling sort(function) in Javascript on an iPhone it doesn't seem to sort. For example:

devices.sort(function(a, b) {
                    return a.name > b.name;
                });

Are there some known limitations or can someone help me how to do this on an iPhone. It seems to work fine in Chrome, IE, Firefox.

A: 

The sort function needs to return -1, 0, or 1.

devices.sort(function(a, b) {
  if (a.name < b.name) {
    return -1;
  } else if (a.name == b.name) {
    return 0; // ambiguous
  } else {
    return 1;
  }
});
Duncan Beevers
Also, check out this binarySearch that allows you to quickly find items in large sorted lists using a custom comparator function.http://www.dweebd.com/javascript/binary-search-an-array-in-javascript/
Duncan Beevers
A: 

You have to explicitly return -1, 0 or 1, as per the definition of this function I guess. My bad.

                    devices.sort(function(a, b) {
                    if (a.name < b.name) return -1;
                    if (a.name > b.name) return 1;
                    return 0;
                });

Works now.

+2  A: 

Your comparison function is broken: It should return a numerical value which has to be negative if a < b, zero if a = b and positive if a > b, ie

function(a, b) {
    return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
}

Your function returns false if a.name < b.name, which will be converted to 0 and therefore means the values should be regarded as equal. It shouldn't work at all, but if it does, this is by coincidence (ie depends on the sorting algorithm and/or input set).

Christoph