Skip to content

Instantly share code, notes, and snippets.

@ugurozpinar
Created March 21, 2014 09:36
Show Gist options
  • Save ugurozpinar/9682734 to your computer and use it in GitHub Desktop.
Save ugurozpinar/9682734 to your computer and use it in GitHub Desktop.
Javascript object array Turkish sorting. Türkçe Sıralama
var arr = [{id:3,title:"Ali"},{id:3,title:"Veli"},{id:3,title:"Vehbi"}];
arr.sort(turkcesiralama);
function turkcesiralama(a, b){
var atitle = a.title;
var btitle = b.title;
var alfabe = "AaBbCcÇçDdEeFfGgĞğHhIıİiJjKkLlMmNnOoÖöPpQqRrSsŞşTtUuÜüVvWwXxYyZz0123456789";
if (atitle.length === 0 || btitle.length === 0) {
return atitle.length - btitle.length;
}
for(var i=0;i<atitle.length && i<btitle.length;i++){
var ai = alfabe.indexOf(atitle[i]);
var bi = alfabe.indexOf(btitle[i]);
if (ai !== bi) {
return ai - bi;
}
}
}
@emresert
Copy link

Thank you for solution. That was useful for me.

@eboyraz
Copy link

eboyraz commented Mar 15, 2023

turkishTextCompare(firstString: string, secondString: string, isDesc = false) {
    const alphabet = 'AaBbCcÇçDdEeFfGgĞğHhIıİiJjKkLlMmNnOoÖöPpQqRrSsŞşTtUuÜüVvWwXxYyZz0123456789';
    const minStringLen = firstString.length > secondString.length ? firstString.length : secondString.length;

    for (let i = 0; i < minStringLen; i++) {
        const fCharPos= alphabet.indexOf(firstString[i]);
        const sCharPos= alphabet.indexOf(secondString[i]);

        if (fCharPos!== sCharPos) {
            return (fCharPos> sCharPos? 1 : -1) * (isDesc ? -1 : 1);
        }
    }

    return 0;
}

@eboyraz
Copy link

eboyraz commented Mar 15, 2023

usage:
const stringList = ["A", "Ç", "C", "Ş", "S"];
stringList.sort((x, y) => turkishTextCompare(x, y));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment