Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.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中的自定义排序_Javascript_Arrays_Sorting - Fatal编程技术网

javascript中的自定义排序

javascript中的自定义排序,javascript,arrays,sorting,Javascript,Arrays,Sorting,(我以前也问过这个问题,但被标记为重复,但该答案不符合我的要求) 我有一个数组a=[“苹果”、“芒果”、“苹果”、“芒果”]。如果我使用a.sort(),结果是 [“苹果”、“芒果”、“苹果”、“芒果”] 但我想要的是 Apple,apple,Mango,mango 记住它不是不区分大小写的排序,因为无论数组中给定元素的顺序如何,输出都应该是 苹果 苹果 芒果 芒果 表示大写字母应在较小的字母之前那么您的比较器需要进行两轮比较 a.sort(function(e1, e2) { var c

(我以前也问过这个问题,但被标记为重复,但该答案不符合我的要求)

我有一个数组
a=[“苹果”、“芒果”、“苹果”、“芒果”]
。如果我使用
a.sort()
,结果是
[“苹果”、“芒果”、“苹果”、“芒果”]

但我想要的是

Apple,apple,Mango,mango
记住它不是不区分大小写的排序,因为无论数组中给定元素的顺序如何,输出都应该是

苹果 苹果 芒果 芒果
表示大写字母应在较小的字母之前

那么您的比较器需要进行两轮比较

a.sort(function(e1, e2) {
  var ce1 = e1.toLowerCase(), ce2 = e2.toLowerCase();
  if (ce1 < ce2) return -1;
  if (ce1 > ce2) return 1;
  // at this point, we know that the two elements are the same
  // except for letter case ...
  if (e1 < e2) return -1;
  if (e1 > e2) return 1;
  return 0;
});
a.sort(函数(e1,e2){
var ce1=e1.toLowerCase(),ce2=e2.toLowerCase();
if(ce1ce2)返回1;
//此时,我们知道这两个元素是相同的
//除了字母箱。。。
if(e1e2)返回1;
返回0;
});

首先,函数在转换为小写后检查这两个元素。如果它们在转换成小写后相等,它将检查原始表单。因此,“苹果”和“苹果”将在第一轮中进行相等的比较,因此将进行排序,以便“苹果”排在第一位。

然后您的比较器需要进行两轮比较

a.sort(function(e1, e2) {
  var ce1 = e1.toLowerCase(), ce2 = e2.toLowerCase();
  if (ce1 < ce2) return -1;
  if (ce1 > ce2) return 1;
  // at this point, we know that the two elements are the same
  // except for letter case ...
  if (e1 < e2) return -1;
  if (e1 > e2) return 1;
  return 0;
});
a.sort(函数(e1,e2){
var ce1=e1.toLowerCase(),ce2=e2.toLowerCase();
if(ce1ce2)返回1;
//此时,我们知道这两个元素是相同的
//除了字母箱。。。
if(e1e2)返回1;
返回0;
});

首先,函数在转换为小写后检查这两个元素。如果它们在转换成小写后相等,它将检查原始表单。因此,在第一轮中,“苹果”和“苹果”将比较相等,因此将进行排序,以使“苹果”排在第一位。

答案确实符合您的要求…[“苹果”、“芒果”、“苹果”、“芒果”]。排序(函数(a,b){返回a.toLowerCase().localeCompare(b.toLowerCase();});返回[“Apple”、“Apple”、“Mango”、“Mango”],因此如果字符串相等,则需要在其中添加一个附加检查,然后再进行一次检查。Pointy的答案非常好。如果您基本上还不熟悉作为排序参数的函数,请查看此处:@peter_the_oak,感谢您提供的链接,它非常有用,答案的可能副本确实满足您的要求…[“Apple”、“Mango”、“Apple”、“Mango”]。排序(函数(a,b){返回a.toLowerCase().localeCompare(b.toLowerCase();});返回[“Apple”、“Apple”、“Mango”、“Mango”],因此如果字符串相等,则需要在其中添加一个附加检查,然后再进行一次检查。Pointy的答案非常好。如果您基本上还不熟悉作为排序参数的函数,请看这里:@peter_the_oak,感谢您的链接,它非常有用,可能会复制“非常感谢”,最后我得到了我需要的谢谢,最后我得到了我需要的