vote up 3 vote down
star
1

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.

flag

4 Answers

vote up 6 vote down
check

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);
link|flag
thanks. Didn't know that sort took a function ref. – Tyrone Slothrop Jul 15 at 3:45
vote up 2 vote down

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

link|flag
vote up 1 vote down

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;
}
link|flag
vote up 1 vote down

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();
link|flag

Your Answer

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.