2017-04-19 45 views
1

我有一个按名称对列表进行排序的排序函数,但我希望每个以下划线开头的项目都分组在顶部。 当按降序排序(Z-A)时,我需要强调下划线到顶部。所以使用正常的localeCompare将不会起作用,因为它会在底部加上下划线。 对于项目名称以下划线开始我推到顶部使用:当对一个对象数组进行排序时,是否可以使用sort()进一步将已推送到顶部的项进行分组?

if(item1.name().indexOf("_") == 0){ 
    res = -1 
} 
if(item2.name().indexOf("_") == 0){ 
    res = 1 
} 

这样做的问题是,所有这些项目都是一起在顶部,但他们都堆砌在一起我需要的是对他们进一步按姓名排序,即按照下划线后面的字母排序。

我也需要这样做,纯粹作为一个单一的排序功能。

+0

只返回'-1'或'1'如果其他商品不符合'_'开始。 –

回答

-1

您可以检查第一个字符并将'_'移至顶部,然后按降序排序。

var array = ['_a', 'a', 'abc', '_d', 'ef']; 
 

 
array.sort(function (a, b) { 
 
    return (b[0] === '_') - (a[0] === '_') || b.localeCompare(a); 
 
}); 
 

 
console.log(array);

0

您的代码不会考虑到这两个项目可以以下划线开始的可能性。有四种可能性:

if both start with "_", return result of comparing with localeCompare 
if item1 starts with "_", it's less than item2 
if item2 starts with "_", it's greater than item1 
otherwise, neither starts with "_", so compare them with localeCompare 

或者,代码:

if (item1.name().indexOf("_") == 0 && item2.name().indexOf("_") == 0) 
    res = item1.name().localeCompare(item2.name()); 
else if (item1.name().indexOf("_") == 0 
    res = -1; 
else if (item2.name().indexOf("_") == 0 
    res = 1; 
else 
    res = item1.name().localeCompare(item2.name()); 
相关问题