WEBDOOD.COM

Javascript Array Sort By String Length

by webdood on Jul.08, 2011, under Arrays, Javascript

Had a need to sort an array of strings by length of each string in descending order.
Simple solution, really. Perhaps may come in handy at a later date.

  ////////////////////////////////////////////////////////////////////////////
  //
  // Array.sortByStringLength() - sorts an array of strings based on length
  // ==========================
  //
  ////////////////////////////////////////////////////////////////////////////
  Array.prototype.sortByStringLength = function() {
    return this.sort( byStringLength )
  }
  function byStringLength(a,b) {//Sort function used by Array.sortByStringLength
    var retVal = 0;
    if (a.length > b.length) { retVal = -1; }
    return retVal;
  }

Shannon Norrell


2 Comments for this entry

  • enzese

    This is incorrect. The function should be:

    function byStringLength(a,b) {
    if(a.length > b.length) { return -1;}
    else if (a.length < b.length) { return 1;}
    else { return 0; }
    }

  • Simon RENOULT

    Shorter version :

    function sortByStringLength(a,b) {
    return (a.length < b.length) ? 1 : 0;
    };

    Shortest version :

    myarray.sort(function(a,b) {return (a.length < b.length) ? 1 : 0; });

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

  • A List Apart
  • Dive into HTML5
  • Javascript: The Good Parts
  • QuirksMode.org