0

I'm building an app which involves a jQuery mobile directory, which loads three sections of names from a JSON file. I'm wondering if there's a way to automatically alphabetize the items from the JSON array. The people who have commissioned the app will need to add items in future, and it would be easier for them if they didn't have to worry about adding items in alphabetical order themselves. I've put slightly different code here, because of IP, but it should work the same way. To clarify, the proper code will only have "name", not "firstName" and lastName", so sorting by last name won't be necessary.

Edit: I realise this question is a duplicate, and I'm not sure I can prove how it's unique, but the solution that worked for me was not given on the other page, so that page wouldn't have answered my question.

html:

<div data-role="page" id="home"> 
            <div data-role="header">
                <h1>Star Trek: The Next Generation</h1>
            </div>
            <div data-role="main" class="ui-content">
                <div data-role="collapsible" data-collapsed="true">
                    <h2>Humans</h2>
                    <ul id="humans" data-role="listview" data-filter="true" data-inset="true" data-icon="user" data-autodividers="true">
                    </ul>
                </div>
                <div data-role="collapsible" data-collapsed="true">
                    <h2>Robots</h2>
                    <ul id="robots" data-role="listview" data-filter="true" data-inset="true" data-icon="gear" data-autodividers="true"> 
                    </ul>
                </div>
                <div data-role="collapsible" data-collapsed="true">
                    <h2>Wesley</h2>
                    <ul id="wesleys" data-role="listview" data-filter="true" data-inset="true" data-icon="forbidden" data-autodividers="true">
                    </ul>
                </div>
            </div>
        </div>

JavaScript:

$(document).ready( function() {
    $.getJSON("assets/js/starTrek.json", function(data){
        $.each(data.enterprise.humans, function(){
            $("ul#humans").append('<li>' + '<a href="#' + this["url"] + '" data-transition="slide">'+ this["firstName"] + ' ' + this["lastName"] + '</a>' + '</li>');
            $("ul#humans").listview("refresh");
        });
        $.each(data.enterprise.robots, function(){
            $("ul#robots").append('<li>' + '<a href="#' + this["url"] + '" data-transition="slide">'+this["firstName"] + ' ' + this["lastName"] + '</a>' + '</li>');
            $("ul#robots").listview("refresh");
        });
        $.each(data.enterprise.wesleys, function(){
            $("ul#wesleys").append('<li>' + '<a href="#' + this["url"] + '" data-transition="slide">'+ this["firstName"] + ' ' + this["lastName"] + '</a>' + '</li>');
            $("ul#wesleys").listview("refresh");
        });
    });
})

JSON:

{
    "enterprise": {
        "humans": [
        { "firstName":"Jean Luc" , "lastName":"Picard" , "url":"picard"}, 
        { "firstName":"Miles" , "lastName":"O'Brien" , "url":"obrien"},
        { "firstName":"Will" , "lastName":"Riker" , "url":"riker"}  
        { "firstName":"Beverly" , "lastName":"Crusher" , "url":"crusher"},
        { "firstName":"Deanna" , "lastName":"Troi" , "url":"troi" },
        { "firstName":"Mr" , "lastName":"Worf" , "url":"worf"},
        ],

    "robots": [
        { "firstName":"Data" , "lastName":" " , "url":"data"}
        ],

    "wesleys": [
        { "firstName":"Wesley" , "lastName":"Crusher" , "url":"wesley"}
        ]
    }
}
Tanya Branagan
  • 551
  • 1
  • 12
  • 21
  • 4
    Possible duplicate of [Sorting an array of JavaScript objects](http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects) – ceejayoz Jan 20 '16 at 23:57
  • 3
    another related question: http://stackoverflow.com/q/881510/1064270 – Gaël Barbin Jan 20 '16 at 23:57
  • Yeah sorry, I just found those. Even after much googling pre-asking. A question for clarification though, how do I achieve this with an external JSON file? I tried one sort function in JavaScript and it didn't know what I was referring to. eg humans. Also not sure how to do it since I have three small arrays in one. – Tanya Branagan Jan 21 '16 at 00:01

2 Answers2

1

Try this:

data.enterprise.humans.sort(function(a, b) {
  return a.firstName.localeComapre(b.firstName);
});
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
1

Probably the most performant solution would be to query the data already sorted (for example if the data comes from a database, this is relatively trivial). You also have the option to sort on the server side. On the front-end you could use for example

data.enterprise.humans.sort(function(first, second) {
    return first.name.localeCompare(second.name);
});

You should do the same for data.enterprise.robots and data.enterprise.wesleys by either repeating the code or writing a loop such as:

for (key in data.enterprise) {
    data.enterprise[key].sort(function(first, second) {
        return first.name.localeCompare(second.name);
    });
}

Note that the latter only works if all the subarrays in data.enterprise contain objects with names.

David Frank
  • 5,918
  • 8
  • 28
  • 43
  • Excuse my ignorance with all this, but I'm getting "ReferenceError: data is not defined" when I try this. Should I put the JSON in the JS file? Edit: never mind that, it worked! I obviously did something stupid. Thanks! – Tanya Branagan Jan 21 '16 at 00:06
  • It's implied that `data` is the return of the callback of your `$.getJSON` function call. Are you making this call in the `$.getJSON` callback? – mariocatch Jan 21 '16 at 00:11
  • I'm not sure, it's an online course and they give us code samples, and they don't always fully explain them. I know I should understand more, but they throw so much at us in the course that there's not always time to do more research into everything. – Tanya Branagan Jan 21 '16 at 20:09