Multi-sorting in underscore

后端 未结 3 851
自闭症患者
自闭症患者 2020-12-20 08:57

I have Array object ArrObject

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

I want to

3条回答
  •  鱼传尺愫
    2020-12-20 09:21

    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);
    }
    

    Then you could simply do this:

    var sorted = data.sort(cmp);
    

    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.

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

    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.

    Demo: http://jsfiddle.net/ambiguous/6tfcQ/

提交回复
热议问题