如何根据每个元素的长度对数组进行排序? [英] How to sort an array based on the length of each element?
问题描述
我有这样一个数组:
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 mean, 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]
。根据规范:
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
});
这篇关于如何根据每个元素的长度对数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!