Sort An Array By Element Length In Javascript

Posted By Weston Ganger

I had a string array that I wanted to sort based on word length.

Here's a simple example using Array's sort function.

var my_array = ['my','super','awesome','list','of','strings'];

my_array.sort(function(a,b){
  return a.length - b.length; //ASC, For Descending order use: b - a
});

console.log(my_array);
// => ['my','of','list','super','awesome','strings']

Related External Links:

Article Topic:Software Development - Javascript

Date:December 31, 2015