Using Javascript with Underscore.js to Sort the other way

前端 未结 4 842
长情又很酷
长情又很酷 2021-02-01 14:01

I\'m using Javascript sort (with Underscore.js):

_.sortBy([\"Bob\", \"Mary\", \"Alice\"], function (name) {return name})
> [\"Alice\", \"Bob\", \         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-01 14:12

    Obviously you should not do this, as it makes far more sense to sort, then reverse the results, but if you really want to sort in reverse order inside the sort function, you could do something like this...

    _.sortBy(["Bob", "Mary", "Alice"], function (a) {
        // split each string into single characters
        // ... then swap for inverse character from unicode range
        // ... and glue the characters back together into an inversely sortable string
        return _.map(a.split(''), function(i){
            return String.fromCharCode(65536 - i.charCodeAt(0));
        }).join('');
    });
    

    ... also worth noting that underscore is subtly different than native javascript sort which has a small cross platform issue regarding consistent sort order...

    If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this. Array.prototype.sort()

    Underscore's .sortBy documentation states:

    Returns a (stably) sorted copy of list. _.sortBy

    Which it does by instead of returning 0 to keep items in order, it returns the index of the left side minus the index of the right side.

    _.sortBy = function(obj, iteratee, context) {
      iteratee = cb(iteratee, context);
      return _.pluck(_.map(obj, function(value, index, list) {
        return {
          value: value,
          index: index,
          criteria: iteratee(value, index, list)
        };
      }).sort(function(left, right) {
        var a = left.criteria;
        var b = right.criteria;
        if (a !== b) {
          if (a > b || a === void 0) return 1;
          if (a < b || b === void 0) return -1;
        }
        return left.index - right.index;
      }), 'value');
    };
    

提交回复
热议问题