首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >缩短自定义JS排序函数

缩短自定义JS排序函数
EN

Code Review用户
提问于 2015-03-06 13:46:52
回答 3查看 89关注 0票数 0

我有一个排序函数,需要以某种方式排序。该位置首先按移动顶部排序,然后是空位置,然后是移动底部。然后,我需要按照它们的优先级进行排序,优先级为1,2,然后为空白。

代码语言:javascript
复制
  widgetInfo = [
['box1','mobile-bottom',''],
['box2','mobile-top','priority-1'],
['box3','mobile-top',''],
['box3','mobile-top',''],
['box4','mobile-bottom',''],
['box2','mobile-top','priority-1'],
['box5','mobile-top','priority-2'],
['box6','','']],
 ['box5','mobile-top','priority-2'];

var newArray = widgetInfo.sort(function(a, b){

  if(a[1] == 'mobile-top'){
    if(b[1] == 'mobile-bottom'){
      return -1;
    }
    else if(b[1] == 'mobile-top'){

      if(a[2] == 'priority-1'){

        if(b[2] == 'priority-1'){
          return 0;
        }
        else if(b[2] == 'priority-2'){
          return -1;
        }
        else{
          return -1;
        }            
      }

      else if(a[2] == 'priority-2'){

        if(b[2] == 'priority-1'){
          return 1;
        }
        else if(b[2] == 'priority-2'){
          return 0;
        }
        else{
          return -1;
        }            
      }

      else{
        return 1;
      }  

    }
    else{
      return -1;
    }
  }
  if(a[1] == 'mobile-bottom'){
   if(b[1] == 'mobile-top'){
     return 1;
   }
    else if(b[1] == 'mobile-bottom'){
     return 0;
   }
    else{
      return 1;
    }
  }      

});

要做到这一点,似乎需要大量的代码,我相信会有更好的方法。有什么建议吗?

EN

回答 3

Code Review用户

发布于 2015-03-06 13:55:32

您可以编写一个函数来比较两个“位置”字符串,以及一个比较“优先级”字符串的函数。然后,通过调用两个已经定义的函数,可以轻松地编写结果比较函数。

现在,对于实际的审查,您不需要在if(b[1] == 'mobile-bottom')的情况下检查if(a[1] == 'mobile-top'),首先检查if(b[1] == 'mobile-top')是否足够,在另一种情况下,只需返回-1。

类似地,if(a[1] == 'mobile-bottom'),您只需要考虑if(b[1] == 'mobile-bottom'),否则,只需返回1。

票数 1
EN

Code Review用户

发布于 2015-03-06 13:58:37

首先检查优先级1是否不相等,然后相应地返回1/-1,否则检查优先级2并重复

如果你到达终点,那么所有的条件都是平等的:

代码语言:javascript
复制
function(a, b){

    if(a[1] != b[1]){
        if(a[1] == 'mobile-bottom' || b[1]== '') //b[1] will be -top or empty => a<b
            return 1;
        else 
            return -1;
    }

    if(a[2]!=b[2]){
        if(a[2] == 'priority-1' || b[2] == '') //b[2] will be -2 => a<b
            return 1;
        else if(
            return -1;
    }

    return 0;
}

可以将针对字符串的测试替换为只检查这些值的函数,然后将其简化为

代码语言:javascript
复制
function(a, b){
    var result = compareMobile(a[1], b[1]);

    if(result != 0){
        return result;
    }

    result = comparePriority(a[2], b[2]);

    return result;
}
票数 1
EN

Code Review用户

发布于 2015-03-06 14:26:20

那么计算优先级哈希呢?

代码语言:javascript
复制
var mobilePrios = ['mobile-top', 'mobile-bottom'];

function calculatePriority(widgInf) {
  return (mobilePrios.indexOf(widgInf[0]) + 2) * 4 + widgInf[1].replace('priority-', '') * 0.10;    
}

对于要比较的两个widgInfo元素,只需调用它,并按返回的值对其进行排序。

票数 0
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/83396

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档