Javascript 如何根据每个元素的长度对数组进行排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10630766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to sort an array based on the length of each element?
提问by ramesh kumar
I have an array like this:
我有一个这样的数组:
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.
我的意思是,我想按每个元素的长度降序排列。
回答by Salman A
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:
您可以使用Array.sort
方法对数组进行排序。可以使用以字符串长度作为排序标准的排序函数,如下所示:
arr.sort(function(a, b){
// ASC -> a.length - b.length
// DESC -> b.length - a.length
return b.length - a.length;
});
Note: sorting ["a", "b", "c"]
by length of string is not guaranteed to return ["a", "b", "c"]
. According to the specs:
注意:["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
});
回答by Bharata
We can use Array.sortmethod to sort this array.
我们可以使用Array.sort方法对这个数组进行排序。
ES5 solution
ES5解决方案
var array = ["ab", "abcdefgh", "abcd"];
array.sort(function(a, b){return b.length - a.length});
console.log(JSON.stringify(array, null, '\t'));
For ascendingsort order:
a.length - b.length
For descendingsort order:
b.length - a.length
对于升序排序:
a.length - b.length
对于降序排序:
b.length - a.length
ES6 solution
ES6解决方案
Attention: not all browsers can understand ES6 code!
注意:并非所有浏览器都能理解 ES6 代码!
In ES6 we can use an arrow function expressions.
在 ES6 中我们可以使用箭头函数表达式。
let array = ["ab", "abcdefgh", "abcd"];
array.sort((a, b) => b.length - a.length);
console.log(JSON.stringify(array, null, '\t'));
回答by shareef
Here is the sort, depending on the length of a string with javascript as you asked:
这是排序,具体取决于您询问的带有 javascript 的字符串的长度:
[the solution of the problem by bubble sort][1]
[冒泡排序问题的解决][1]
[1]: http://jsfiddle.net/sssonline2/vcme3/2/enter code here
[1]:http: //jsfiddle.net/sssonline2/vcme3/2/enter code here
回答by Nico
Based on Salman's answer, I've written a small function to encapsulate it:
根据 Salman 的回答,我写了一个小函数来封装它:
function sortArrayByLength(arr, ascYN) {
arr.sort(function (a, b) { // sort array by length of text
if (ascYN) return a.length - b.length; // ASC -> a - b
else return b.length - a.length; // DESC -> b - a
});
}
then just call it with
然后就用
sortArrayByLength( myArray, true );
Note that unfortunately, functions can/should not be added to the Array prototype, as explained on this page.
请注意,不幸的是,函数可以/不应该添加到 Array 原型中,如本页所述。
Also, it modified the array passed as a parameter and doesn't return anything. This would force the duplication of the array and wouldn't be great for large arrays. If someone has a better idea, please do comment!
此外,它修改了作为参数传递的数组并且不返回任何内容。这将强制重复阵列,并且对于大型阵列来说不是很好。如果有人有更好的想法,请发表评论!
回答by Nico
I adapted @shareef's answer to make it concise. I use,
我改编了@shareef 的答案以使其简洁。我用,
.sort(function(arg1, arg2) { return arg1.length - arg2.length })
.sort(function(arg1, arg2) { return arg1.length - arg2.length })
回答by Rishabh Gupta
#created a sorting function to sort by length of elements of list
def sort_len(a):
num = len(a)
d = {}
i = 0
while i<num:
d[i] = len(a[i])
i += 1
b = list(d.values())
b.sort()
c = []
for i in b:
for j in range(num):
if j in list(d.keys()):
if d[j] == i:
c.append(a[j])
d.pop(j)
return c
回答by Hi?n
This code should do the trick:
这段代码应该可以解决问题:
var array = ["ab", "abcdefgh", "abcd"];
array.sort(function(a, b){return b.length - a.length});
console.log(JSON.stringify(array, null, '\t'));
回答by Mad Scientist
<script>
arr = []
arr[0] = "ab"
arr[1] = "abcdefgh"
arr[2] = "sdfds"
arr.sort(function(a,b){
return a.length<b.length
})
document.write(arr)
</script>
The anonymous function that you pass to sort tells it how to sort the given array.hope this helps.I know this is confusing but you can tell the sort function how to sort the elements of the array by passing it a function as a parameter telling it what to do
您传递给 sort 的匿名函数告诉它如何对给定的数组进行排序。希望这会有所帮助。我知道这很令人困惑,但您可以通过将函数作为参数传递给 sort 函数来告诉它如何对数组元素进行排序它该怎么做