且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据每个元素的长度对数组进行排序?

更新时间:2021-07-30 22:47:40

您可以使用 Array.sort 排序数组的方法。将字符串长度视为排序标准的排序函数可以按如下方式使用:

You can use Array.sort method to sort the array. A sorting function that considers the length of string as the sorting criteria can be used as follows:

arr.sort(function(a, b){
  // ASC  -> a.length - b.length
  // DESC -> b.length - a.length
  return b.length - a.length;
});






注意:排序 [ a,b,c] 按字符串长度不保证返回 [a,b,c] 。根据规范


Note: sorting ["a", "b", "c"] by length of string is not guaranteed to return ["a", "b", "c"]. According to the specs:


排序不一定稳定(也就是说,比较
等于的元素不一定保持原始顺序。)

The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order).

如果目标是按长度排序,然后按字典顺序排序,则必须指定其他条件:

If the objective is to sort by length then by dictionary order you must specify additional criteria:

["c", "a", "b"].sort(function(a, b) {
  return a.length - b.length || // sort by length, if equal then
         a.localeCompare(b);    // sort by dictionary order
});