使用 Javascript 和 Underscore.js 以另一种方式排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8703914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:09:59  来源:igfitidea点击:

Using Javascript with Underscore.js to Sort the other way

javascriptsortingunderscore.js

提问by Harry

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

我正在使用 Javascript sort(使用 Underscore.js):

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

I would like the array to return the other way. How do I do that?

我希望数组以另一种方式返回。我怎么做?

["Mary", "Bob", "Alice"]

[“玛丽”、“鲍勃”、“爱丽丝”]

I don't want to reverse it after it's sorted - I want it to be created the other way around the first time.

我不想在排序后反转它 - 我希望它第一次以相反的方式创建。

Thanks.

谢谢。

采纳答案by Felix Loether

I would just do what Underscore does under the hood: use the Array#sortmethod.

我只会做 Underscore 在幕后所做的事情:使用Array#sort方法。

["Bob", "Mary", "Alice"].sort(function (a, b) {
    if (a < b) return 1;
    if (b < a) return -1;
    return 0;
});

Or if you don't want the original array modified, clone it first:

或者,如果您不想修改原始数组,请先克隆它:

_.clone(["Bob", "Mary", "Alice"]).sort(...)

回答by h--n

Instead of throwing underscorejs away, I'd rather use it together with Array.reverseto utilize the best of both.

与其扔掉 underscorejs,我宁愿将它与Array.reverse两者结合使用,以充分利用两者的优点。

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

回答by Billy Moon

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...

显然你不应该这样做,因为排序更有意义,然后反转结果,但如果你真的想在 sort 函数中以相反的顺序排序,你可以做这样的事情......

_.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...

...还值得注意的是,下划线与原生 javascript 排序略有不同,后者在一致排序顺序方面存在一个小的跨平台问题...

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()

如果 compareFunction(a, b) 返回 0,则使 a 和 b 彼此保持不变,但相对于所有不同元素进行排序。注意:ECMAscript 标准不保证这种行为,因此并非所有浏览器(例如至少可以追溯到 2003 年的 Mozilla 版本)都尊重这一点。Array.prototype.sort()

Underscore's .sortBydocumentation states:

Underscore 的.sortBy文档说明:

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

返回列表的(稳定)排序副本。_。排序方式

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

它不是返回0以保持项目有序,而是返回左侧的索引减去右侧的索引。

_.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');
};

回答by FMD

You can do this with a 1 liner in ES6, just change the >depending on the direction you want.

你可以用 ES6 中的 1 liner 来做到这一点,只需>根据你想要的方向改变它。

.sort()is supported since IE6 and you just pass a function which returns 1 or -1;

.sort()自 IE6 起支持,您只需传递一个返回 1 或 -1 的函数;

["Bob", "Mary", "Alice].sort((a, b) => a > b ? 1 : -1);