-4

I have this code

function Human(firstName,lastName,age)
{
    this.firstName = firstName;
    this.lastName =  lastName;
    this.age = age;
}

var firstHuman = new Human("Ivan","Ivanov",25);
var secondHuman = new Human("Petar","Petrov",34);
var thirdHuman = new Human("Ivailo", "Stoyanov",28);
var forthHuman = new Human("Petar", "Tudjarov",50);
var fifthHuman = new Human("Hari", "Qvorov",20);

var Humans = new Array (firstHuman,secondHuman,thirdHuman,forthHuman,fifthHuman);

how can i sort them by their firstName so fifthHuman (H is smallest in alphabet) to be first in array

Yoan Dinkov
  • 531
  • 1
  • 5
  • 17
  • 4
    [And what have you tried?](http://whathaveyoutried.com) –  Mar 28 '13 at 16:30
  • Humans.sort(function(person){return person.firstName}); Humans.sort(function(firstPerson,secondPerson){return firstPerson.firstName - secondPerson.firstName} – Yoan Dinkov Mar 28 '13 at 16:30
  • You may find this post usefull : http://stackoverflow.com/questions/5002848/how-to-define-custom-sort-function-in-javascript – Laurent S. Mar 28 '13 at 16:32
  • 1
    I recommend to [have a look at the `.sort` documentation](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort), which explains how the callback function must be structured. – Felix Kling Mar 28 '13 at 16:32
  • @Daemonyoyo Why would you try to subtract strings?? Stop mindlessly copy-pasting code and **think about what you're doing**. –  Mar 28 '13 at 16:36
  • You can find some useful answers to this topic here: **[Sorting objects in an array by a field value in JavaScript](http://stackoverflow.com/a/26759350/2247494)** – jherax Nov 05 '14 at 16:02

1 Answers1

3
Humans.sort(function(a, b){return a.firstName > b.firstName});

http://jsfiddle.net/3wyBc/

Cristi Pufu
  • 9,002
  • 3
  • 37
  • 43