Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 对对象数组进行排序时,是否可以使用sort()对推到顶部的项目进行进一步分组?_Javascript_Sorting - Fatal编程技术网

Javascript 对对象数组进行排序时,是否可以使用sort()对推到顶部的项目进行进一步分组?

Javascript 对对象数组进行排序时,是否可以使用sort()对推到顶部的项目进行进一步分组?,javascript,sorting,Javascript,Sorting,我有一个排序函数,可以按名称对列表进行排序,但我希望每个以下划线开头的项目都分组在顶部。 在按降序(Z-a)排序时,我需要强制将下划线置于顶部。因此,使用普通的localeCompare将无法工作,因为它会在底部添加下划线。 对于以下划线开头的项目名称,我使用以下命令推到顶部: if(item1.name().indexOf("_") == 0){ res = -1 } if(item2.name().indexOf("_") == 0){ res = 1 } 问题是,所有这些

我有一个排序函数,可以按名称对列表进行排序,但我希望每个以下划线开头的项目都分组在顶部。 在按降序(Z-a)排序时,我需要强制将下划线置于顶部。因此,使用普通的localeCompare将无法工作,因为它会在底部添加下划线。 对于以下划线开头的项目名称,我使用以下命令推到顶部:

if(item1.name().indexOf("_") == 0){
    res = -1
}
if(item2.name().indexOf("_") == 0){
    res = 1
}
问题是,所有这些项目都在顶部,但它们都杂乱无章,我需要的是它们按名称进一步排序,即按下划线后面的字母排序


我还需要纯粹作为一个单独的排序函数来执行此操作。

您可以检查第一个字符,并将带有
的字符移到顶部,然后按降序排序

var数组=[''u a','a','abc','u d','ef'];
array.sort(函数(a,b){
return(b[0]==''.''-(a[0]=='.''.'.| b.localeCompare(a);
});

console.log(数组)
您可以检查第一个字符,将带有
'
的字符移到顶部,然后按降序排序

var数组=[''u a','a','abc','u d','ef'];
array.sort(函数(a,b){
return(b[0]==''.''-(a[0]=='.''.'.| b.localeCompare(a);
});

console.log(数组)您的代码没有考虑两个项目都以下划线开头的可能性。有四种可能性:

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

您的代码没有考虑这两个项目都以下划线开头的可能性。有四种可能性:

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

如果另一项不是以
\uu
开头,则仅返回
-1
1
。如果另一项不是以
\uu
开头,则仅返回
-1
1