ram*_*mar 81 javascript arrays sorting string
我有这样一个数组:
arr = []
arr[0] = "ab"
arr[1] = "abcdefgh"
arr[2] = "abcd"
Run Code Online (Sandbox Code Playgroud)
排序后,输出数组应为:
arr[0] = "abcdefgh"
arr[1] = "abcd"
arr[2] = "ab"
Run Code Online (Sandbox Code Playgroud)
我的意思是,我希望按每个元素长度的降序排列.
Sal*_*n A 207
您可以使用Array.sort
方法对数组进行排序.将字符串长度视为排序标准的排序函数可以使用如下:
arr.sort(function(a, b){
// ASC -> a.length - b.length
// DESC -> b.length - a.length
return b.length - a.length;
});
Run Code Online (Sandbox Code Playgroud)
注意:["a", "b", "c"]
不保证按字符串长度排序["a", "b", "c"]
.根据规格:
排序不一定稳定(即,比较相等的元素不一定保持原始顺序).
如果目标是按长度排序,然后按字典顺序排序,则必须指定其他条件:
["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
});
Run Code Online (Sandbox Code Playgroud)
我们可以使用Array.sort方法对这个数组进行排序。
var array = ["ab", "abcdefgh", "abcd"];
array.sort(function(a, b){return b.length - a.length});
console.log(JSON.stringify(array, null, '\t'));
Run Code Online (Sandbox Code Playgroud)
对于升序排序:
a.length - b.length
对于降序排序:
b.length - a.length
注意:并非所有浏览器都能理解 ES6 代码!
在 ES6 中我们可以使用箭头函数表达式。
let array = ["ab", "abcdefgh", "abcd"];
array.sort((a, b) => b.length - a.length);
console.log(JSON.stringify(array, null, '\t'));
Run Code Online (Sandbox Code Playgroud)
使用现代 JavaScript,你可以这样做:
降序
const arr = [
"ab",
"abcdefgh",
"abcd",
"abcdefghijklm"
];
arr.sort((a, b) => b.length - a.length);
console.log(JSON.stringify(arr, null, 2));
Run Code Online (Sandbox Code Playgroud)
升序- 只需切换a
withb
const arr = [
"ab",
"abcdefgh",
"abcd",
"abcdefghijklm"
];
arr.sort((a, b) => a.length - b.length);
console.log(JSON.stringify(arr, null, 2));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
74020 次 |
最近记录: |