Javascript

Sort An Array By Element Length In Javascript

Posted by Weston Ganger on December 31, 2015

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:


Posted in Javascript and Tagged with javascript array sort 


Need help on your next project or application?

I specialize in Ruby-on-Rails, AngularJS, Javascript, Bootstrap, and Hybrid Mobile Apps with Cordova & Ionic.

Contact Me

Recommended Posts