js 字符数组如何按照字符长度排序?
有没有比较好的方法推荐,自己写了一个过于麻烦?
var arr = ['sdqwe1232','123','weqw123'];
console.log(arr.sort(function(a,b){
return a.length - b.length;
}));
看了一下楼上的回答,每比一次都要去取一次 .length
,为啥不先存一遍:
const arr = ['132','qwedd','q','2r','qwd']
const rtn = arr.map(i => ({raw: i, len: i.length}))
.sort((p, n) => n.len - p.len)
.map(i => i.raw)
console.log(rtn) // [ 'qwedd', '132', 'qwd', '2r', 'q' ]
学习了!
let arr = ['1234','12','4578','0986','qwerasd']
arr.sort((a, b) => {
if (a.length > b.length) {
return 1
}
if (a.length < b.length) {
return -1
}
return 0
})
13 回答12.9k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
2 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
6 回答1.1k 阅读
3 回答1.3k 阅读✓ 已解决