Javascript sorting with function not working on iPhone

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

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

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

+5
source share
3 answers

The comparison function is violated: it must return a numerical value, which must be negative if a < b, zero, if a = bpositive, if a > b, i.e.

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

false, a.name < b.name, 0 , , , . , , (.. / ).

+8

-1, 0 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;
  }
});
0

You must explicitly return -1, 0, or 1, as is clear from the definition of this function. My bad.

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

It works now.

0
source

All Articles