【问题标题】:How to sort 2 types of values for an array? [duplicate]如何对数组的两种类型的值进行排序? [复制]
【发布时间】:2013-02-07 11:57:51
【问题描述】:

我正在尝试按字母顺序对项目进行排序。但是,我也想对项目类型进行排序。

例如:

我想要

  type     sortValue

blockItem   a test1
blockItem   a test2
blockItem   b test3
imageItem   a image
imageItem   b image
imageItem   c image
imageItem   s image
textItem    a text
textItem    b text
textItem    c text

我的代码会做这样的事情。

  type     sortValue

blockItem   a test1
blockItem   a test2
imageItem   a image
textItem    a text
blockItem   b test3
imageItem   b image
textItem    b text
imageItem   c image
textItem    c text
imageItem   s image

我的排序函数

array contains type and sortvalue

array=array.sort(sortFunction);

function sortFunction(groupA, groupB) {

    if (groupA.sortValue > groupB.sortValue) {
        return 1;
    } else if (groupA.sortValue < groupB.sortValue) {
        return -1;
    }

    return 0;
}

它只对文本进行排序,而不是对类型进行排序。我想知道是否有办法做到这一点。非常感谢!

【问题讨论】:

    标签: javascript sorting


    【解决方案1】:

    使用第二个键比较第一个是否相等:

    function sortFunction(a, b) {
        if (a.key1 > b.key1) {
            return +1;
        } else if (a.key1 < b.key1) {
            return -1;
        } else if (a.key2 > b.key2) {
            return +1;
        } else if (a.key2 < b.key2) {
            return -1;
        } else 
        ...
        } else if (a.keyN > b.keyN) {
            return +1;
        } else if (a.keyN < b.keyN) {
            return -1;
        } else {
           return 0;
        }   
    }
    

    或者,为了更好的可读性:

    function sortFunction(a, b) {
        if (a.key1 > b.key1) {
            return +1;
        } else if (a.key1 < b.key1) {
            return -1;
        }
    
        if (a.key2 > b.key2) {
            return +1;
        } else if (a.key2 < b.key2) {
            return -1;
        }
        ...
    
        if (a.keyN > b.keyN) {
            return +1;
        } else if (a.keyN < b.keyN) {
            return -1;
        }
    
        return 0;
    }
    

    【讨论】:

    • 不错。顺便说一句,您可以将其缩短为 return (a.key1&gt;b.key1)-(a.key1&lt;b.key1) || (a.key2&gt;b.key2)-(a.key2&lt;b.key2) || … || (a.keyN&gt;b.keyN)-(a.keyN b.keyN);
    【解决方案2】:
    if (groupA.type == groupB.type) {
        /* your code */
    }
    else if (groupA.type > groupB.type) {
        return 1;
    }
    else if (groupA.type < groupB.type) {
        return -1;
    }
    
    return 0;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2011-12-09
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      相关资源
      最近更新 更多