0

I have a function that gets and filters a JSON string to list each chapter of an audio book.

function drawChaperList(book) {
    $(".player-book-chapters").html( " ");//clear chapter list
    $.each(book.files, function(key, bookChapter){  
        if(bookChapter.format === "128Kbps MP3"){
            console.log(key, bookChapter.track);
            var eachBookChapter = $("<li class='chapter'></li>").appendTo('.player-book-chapters');
            eachBookChapter.data("track", bookChapter.track).append("<a title='"+bookChapter.title+"' class='bookChapter' href='"+bookChapter.name+"'>"+ bookChapter.title +"</a>");
        }
    });
}

The result is all the chapters I want but in no particular order. This is my result:

    Key, Track #
    9 "3"
    16 "6"
    17 "2"
    20 "1"
    26 "5"
    27 "4"

How can I sort and display the results by the track #? I understand that .sort doesn't work on objects and after bumping my head with this for a bit I hoped someone can help in the right direction.

Thanks

Ionko Gueorguiev
  • 302
  • 4
  • 18
  • http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value – sumit Feb 05 '17 at 23:49
  • Already tried that, it doesn't work inside my if statement and it doesn't work outside because not all results have a .track property. – Ionko Gueorguiev Feb 05 '17 at 23:54
  • paste the code snippet of what you have tried – sumit Feb 05 '17 at 23:56
  • Write a sorting algorithm (many online) that looks at the track # and sorts the data accordingly? As suggested, though, you'll have to move the data to an array – PsychoMantis Feb 05 '17 at 23:58
  • keysSorted = Object.keys(bookChapter.track).sort(function(a,b){return bookChapter.track[a]-bookChapter.track[b]}) console.log(keysSorted); As expected it only returns a single value, because there is only 1 .track property in each chapter. The accepted answer returned errors. Don't have that in my SC. – Ionko Gueorguiev Feb 06 '17 at 00:02

0 Answers0