views:

42

answers:

1

I am creating an Android app using PhoneGap and jqTouch, and I have a JSON object containing a word along with a language which that word is in. How can I sort this alphabetically, by the column on the right (the language), using Javascript? The end result should be Afrikaans as the first entry and Zulu as the last.

var languages = {
    "Hello" :   "English",
    "Bonjour"   :   "French",
    "Hola"  :   "Spanish",
    "السّلام عليكم" :   "Arabic",
    "Haai"  :   "Afrikaans",
    "Nei ho"    :   "Cantonese".
    "Goddag"    :   "Danish",
    "Goede dag" :   "Dutch",
    "Saluton"   :   "Esperanto",
    "Hei"   :   "Finnish",
    "Guten tag" :   "German",
    "Gia'sou"   :   "Greek",
    "Aloha" :   "Hawaiian",
    "Hebrew"    :   "Shalom",
    "Namaste"   :   "Hindi",
    "Halo"  :   "Indonesian",
    "Aksunai"   :   "Inuit",
    "Dia dhuit" :   "Irish",
    "Salve" :   "Spanish",
    "Kon-nichiwa"   :   "Japanese",
    "An-nyong Ha-se-yo" :   "Korean",
    "Mandarin"  :   "Ni hao",
    "Hallo" :   "Norweigan",
    "Dzien' dobry"  :   "Polish",
    "Jambo" :   "Swahili",
    "Hej"   :   "Swedish",
    "Sa-wat-dee"    :   "Thai",
    "Merhaba"   :   "Turkish",
    "Vitayu"    :   "Ukrainian",
    "Hylo"  :   "Welsh",
    "Sholem aleychem"   :   "Yiddish",
    "Sawubona"  :   "Zulu"
}

Thanks for your help guys :)

+3  A: 

JavaScript does not guarantee any ordering of object properties. So you'll need to create an array which numerically indexes each entry.

E.g.:

var list = [];
for (x in languages) {
  list.push({lang: languages[x], word: x});
}

Then, to sort by language, you can:

list = list.sort(function (a, b) { return a.lang < b.lang; });
Matt