排序根据每个元件的长度的阵列 [英] 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]
是字符串的长度不保证返回 [一,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屋!