如何根据每个元素的长度对数组进行排序? [英] How to sort an array based on the length of each element?

查看:30
本文介绍了如何根据每个元素的长度对数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组:

arr = []
arr[0] = "ab"
arr[1] = "abcdefgh"
arr[2] = "abcd"

排序后,输出数组应该是:

After sorting, the output array should be:

arr[0] = "abcdefgh"
arr[1] = "abcd"
arr[2] = "ab"  

我想要每个元素长度的降序顺序.

I want in the descending order of the length of each element.

推荐答案

您可以使用 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"].根据规范:

排序不一定稳定(即比较的元素相等不一定保持其原始顺序).

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

这篇关于如何根据每个元素的长度对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆