userimage

Sort array of objects by string property value in JavaScript

I want to sort an array of JavaScript objects by the value of l_name in JavaScript?

var objs = [ 

    { f_name: "Lazslo", l_name: "Jamf"     },

    { f_name: "Pig",    l_name: "Bodine"   },

    { f_name: "Pirate", l_name: "Prentice" }

];

The sort(a,b), only seems to work on strings and numbers. Do I need to add a toString method to my objects?

userimage

Just we need to write our comparison function.

function compare(a,b) {
          if (a.last_name< b.last_name)
            return -1;
          if (a.last_name> b.last_name)
            return 1;
          return 0;
        }


Answer is