How are js character arrays sorted by character length?

js 
Oct.22,2021

let arr = ['132','qwedd','q','2r','qwd'];
arr.sort(function(a,b){
    return a.length>b.length;
})
//["q", "2r", "132", "qwd", "qwedd"]

var arr = ['sdqwe1232','123','weqw123'];
console.log(arr.sort(function(a,b){
    return a.length - b.length;
}));

take a look at the answer upstairs and pick it up .length every time. Why not save it first:

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' ]
< hr >

study!


arr.forEach(s => setTimeout(console.log, s.length, s))
Menu