views:

1658

answers:

4

Say I have an array of JS objects:

var objs = [ { first_nom: 'Lazslo',last_nom: 'Jamf' },
            { first_nom: 'Pig', last_nom: 'Bodine'  },
            { first_nom: 'Pirate', last_nom: 'Prentice' }
           ];

How can I sort them by the value of last_nom in JavaScript. I know about sort(a,b) but that only seems to work on strings and numbers. Do I need to add a toString method to my objects?

Thanks in advance.

+2  A: 

This script allows you to do just that unless you want to write your own comparison function or sorter:

http://www.thomasfrank.se/sorting_things.html

Baversjo
+8  A: 

It's easy enough to write your own comparison function:

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

objs.sort(compare);
Wogan
thanks. Didn't know that sort took a function ref.
Tyrone Slothrop
Or inline: objs.sort(function(a,b) {return (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0);} );
Marco Demajo
+1  A: 

If you have duplicate last names you might sort those by first name-

obj.sort(function(a,b){
  if(a.last_nom< b.last_nom) return -1;
  if(a.last_nom >b.last_nom) return 1;
  if(a.first_nom< b.first_nom) return -1;
  if(a.first_nom >b.first_nom) return 1;
  return 0;
}
kennebec
+1  A: 

Instead of using a custom comparison function, you could also create an object type with custom toString() method (which is invoked by the default comparison function):

function Person(firstName, lastName) {
    this.firtName = firstName;
    this.lastName = lastName;
}

Person.prototype.toString = function() {
    return this.lastName + ', ' + this.firstName;
}

var persons = [ new Person('Lazslo', 'Jamf'), ...]
persons.sort();
Christoph