Javascript Data Type How to - Sort Arrays By Their Length








Question

We would like to know how to sort Arrays By Their Length.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
<!-- w  ww  .  j a  va  2 s. c om-->
var
  a = ["a", "a"];
  b = ["b", "b", "b", "b"],
  c = ["c", "c", "c"],
  d = ["d"],
  container = [a, b, c, d];

container.sort(function (a, b) {
  return b.length - a.length;
});
document.writeln(container);

</script>
</head>
<body>
</body>
</html>

The code above is rendered as follows: