下划线中的多重排序 [英] Multi-sorting in underscore

查看:115
本文介绍了下划线中的多重排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Array对象 ArrObject

object = {
    Active: true, // type: boolean
    Code: '12345'   // type: string
}

我想按 Active 字段排序此数组,然后代码。我需要帮助才能使用 underscoreJs

I want to sort this array by Active field then Code. I need help to do that with underscoreJs.

更新

我的数据:

data = [
{
    Code: "Code0",
    Description: "Description0",
    IsActive: true,
    id: 0
},
{
    Code: "Code1",
    Description: "Description1_edit",
    IsActive: true,
    id: 1
},
{
    Code: "Code5",
    Description: "Description5_edit",
    IsActive: false,
    id: 2
}]


推荐答案

我只是使用 数组#sort ,带有简单的比较器功能:

I'd just use Array#sort with a simple comparator function:

function cmp_bool(a, b) {
    return a == b ?  0
         : a      ? -1
         :          +1
}
function cmp_str(a, b) {
    return a == b ?  0
         : a <  b ? -1
         :          +1
}
function cmp(a, b) {
    return cmp_bool(a.IsActive, b.IsActive)
        || cmp_str( a.Code,     b.Code);
}

然后你可以这样做:

var sorted = data.sort(cmp);

如果您需要能够切换代码排序顺序然后你只需要一个反转版本的 cmp_str (比如 cmp_str_reverse )和一个<$ c的版本$ c> cmp 使用 cmp_str_reverse 而不是 cmp_str

If you need to be able to switch the Code sort order then you just need a reversed version of cmp_str (say cmp_str_reverse) and a version of cmp that uses cmp_str_reverse instead of cmp_str.

如果你必须使用 _。sortBy 然后你只需要提出一个值来排序,如下所示:

If you must use _.sortBy then you just need to come up with a value to sort by, something like this:

function combined(obj) {
    return (obj.IsActive ? 'a' : 'b')
         +  obj.Code;
}
var sorted = _(data).sortBy(combined);

这个问题是反转代码<更难/ code>订购。我想你可能会对字符串的字符做一点点麻烦但这只会让你想知道你在六个月内查看代码时你正在做什么。 _。sortBy 是一种符号方便,你不必强迫一切都适合你手头的任何便利。

The problem with this is that it is much harder to reverse the Code ordering. I suppose you could do a big mess of bit twiddling on the string's characters but that would just leave you wonder just what you were doing when you look at the code in six months. _.sortBy is a notational convenience, you don't have to force everything to fit whatever conveniences you have on hand.

演示: http://jsfiddle.net/ambiguous/6tfcQ/

这篇关于下划线中的多重排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆