Javascript Data Type How to - Sort string array by word length








Question

We would like to know how to sort string array by word length.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!--  ww  w. ja v  a  2  s  . co m-->
var longWords = ["A", "AA", "AAA", "AAAA", "AAAAA"];
longWords.sort(function (a, b) {
    return a.length < b.length;
});
document.writeln(longWords);
</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: