Search code examples
javascriptprototypejs

Sorting an object using prototype


I have an object array called Persons and would like to sort by one of its members, I am new to javascript prorotype and not sure how to do this. The object looks like this:

[ Object { EntityId=0, Name="Edibert", Number="1234", Value=""}]

[ Object { EntityId=0, Name="Jairo", Number="1234", Value=""}]

So it has a few more items there for that array of object Persons. I know i can access the name by doing something like this.Persons[0].Name. But how can i sort it by Name?.

thank you so much


Solution

  • You can do this without Prototype:

    Persons.sort(function(a,b) {
        if(a.Name < b.Name) { return -1; }
        if(a.Name > b.Name) { return 1; }
        return 0;
    });
    

    Use any properties of the object you want from within the sort function, so long as you return one of the following values:

    • (-1) if a is to appear before b in the final array
    • (1) if a is to appear after b
    • (0) if the two items being sorted are identical

    In reality, any negative or positive number would work as a return value, but -1 and 1 are conventional.