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;
}
}
}
@ramesaliyev
Copy link

Its worked for me. Thanks!

@ibrahimcanbaz
Copy link

You can also try ;

arr.sort(function (a, b) {
  return a.title.localeCompare(b.title);
});

@mhkoca
Copy link

mhkoca commented Jun 28, 2018

So thanks. But in this case numbers and lower chars was later. For example "AZİZ" was before "aslan".
For this I changed script like below(Maybe lower chars could be remove):

function turkcesiralama(a, b){
    var atitle = a.Description;
    var btitle = b.Description;
    var alfabe = "0123456789AaBbCcÇçDdEeFfGgĞğHhIıİiJjKkLlMmNnOoÖöPpQqRrSsŞşTtUuÜüVvWwXxYyZz";
    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].toUpperCase());
        var bi = alfabe.indexOf(btitle[i].toUpperCase());
        if (ai !== bi) {
            return ai - bi;
        }
    }
}

@mferten
Copy link

mferten commented Feb 24, 2019

Thank you very much. Eksik olma. MariaDB'de saclarimi yolmaktan kurtardin beni. Sihir gibi (worked like a charm)
www.k12k20.com Turkce olarak www.k12k20tr.com (ayni mantik once Slovak k12k20sk.com ve her hangi bir dil icin tekrar edecek).

Ulke adlarini (work in progress yet) siraladim kolayca:

testingFullNames (below: asigida) MariaDB'nin "eksik" siralamasi. "Cabo Verde", "Çad", "Cebelitarık", "Çekya", "Cezayir", "Cibuti", "Çin",

Senin kodun JSON degil yalin Array hali ile dogru siralamayi verdi:
51: "Cabo Verde"
52: "Cebelitarık"
53: "Cezayir"
54: "Cibuti"
55: "Çad"
56: "Çekya"
57: "Çin"

var alfabe = "AaBbCcÇçDdEeFfGgĞğHhIıİiJjKkLlMmNnOoÖöPpQqRrSsŞşTtUuÜüVvWwXxYyZz0123456789";
function turkcesiralama(a, b) { console.log(a + " " + b);
var ai = alfabe.indexOf(a.substring(0,1));
var bi = alfabe.indexOf(b.substring(0,1));
if (ai !== bi) {
return ai - bi;
}
}
testingFullNames = testingFullNames.sort(turkcesiralama);
console.log(testingFullNames);

("eksik" siralanmis
var testingFullNames = ["ABD Minor Outlying Adaları",
"Afganistan",
"Aland Adası",
"Almanya",
"Amerika Birleşik Devletleri",
"Amerikan Bakire Adaları",
"Amerikan Samao",
"Andorra",
"Angola",
"Anguilla",
"Antarktika Antlaşması Sistemi",
"Antigua ve Barbuda",
"Arjantin",
"Arnavutluk",
"Aruba",
"Avustralya",
"Avusturya",
"Az Marten",
"Azerbaycan",
"Aziz Bartelemi",
"Aziz Kits ve Nevis",
"Aziz Martin",
"Aziz Piyer ve Mikelon",
"Aziz Vincen ve Grenadin",
"Azize Helena",
"Azize Luciya",
"Bahamalar",
"Bahreyn",
"Bangaldeş",
"Barbados",
"Batı Sahara",
"Belarus",
"Belçika",
"Belize",
"Benin",
"Bermuda",
"Birleşik Arap Emirlikleri",
"Birleşik Krallık",
"Bolivya",
"Bonaire Sint Eustatius ve Saba",
"Bosna Hersek",
"Botsvana",
"Bouvet Adası",
"Brezilya",
"Britanya Bakire Adaları",
"Britanya Hint Okyanus Alanı",
"Bruney",
"Bulgaristan",
"Burkina Faso",
"Burundi",
"Butan",
"Cabo Verde",
"Çad",
"Cebelitarık",
"Çekya",
"Cezayir",
"Cibuti",
"Çin",
"Danimarka",
"Doğu Timor",
"Dominik Cumhuriyeti",
"Dominika",
"Ekvator",
"Ekvator Ginesi",
"El Salvador",
"Endonezya",
"Eritre",
"Ermenistan",
"Estonya",
"Esvatini",
"Etiyopya",
"Falkland Adaları",
"Faroye Adaları",
"Fas",
"Fiji",
"Filipinler",
"Filistin Devleti",
"Finlandiya",
"Fransa",
"Fransız GÜney ve Antartik Alanı",
"Fransız Guyana",
"Fransız Polenezya",
"Gabon",
"Gambiya",
"Gana",
"Gine",
"Gine Bissau",
"Görnse",
"Grenada",
"Grönland",
"Guadelup",
"Guatemala",
"Güney Afrika Cumhuriyeti",
"Güney Jorgiya ve GÜney Sandavic Adaları",
"Güney Kore",
"Güney Sudan",
"Gürcistan",
"Guyam",
"Guyana",
"Haiti",
"Hindistan",
"Hırvatistan",
"Hollanda",
"Honduras",
"Hong Kong",
"Hörd ve MekDonal Adaları",
"Irak",
"İran",
"İrlanda",
"İspanya",
"İsrail",
"İsveç",
"İsviçre",
"İtalya",
"İzlanda",
"Jamaika",
"Japonya",
"Jörsiy",
"Kamboçya",
"Kamerun",
"Kanada",
"Kanarya Adaları",
"Karadağ",
"Katar",
"Kazakistan",
"Kenya",
"Kiribati",
"Kıbrıs",
"Kırgızistan",
"Kokos Adası",
"Kolombiya",
"Komorlar",
"Kongo Cumhuriyeti",
"Kongo Demokratik Cumhuriyeti",
"Kosova",
"Kosta Rika",
"Kotdivuar",
"Küba",
"Kuk Adaları",
"Kuraço",
"Kuveyt",
"Kuzey Kıbrıs Türk Cumhuriyeti",
"Kuzey Kore",
"Kuzey Mariyana Adaları",
"Laos",
"Lesotho",
"Letonya",
"Liberya",
"Libya",
"Lihtenştayn",
"Litvanya",
"Lübnan",
"Lüksemburg",
"Macaristan",
"Madagaskar",
"Makau",
"Makedonya",
"Malavi",
"Maldivler",
"Malezya",
"Mali",
"Malta",
"Man Adası",
"Marşal Adaları",
"Martinik",
"Mayot",
"Meksika",
"Mikronezya",
"Mısır",
"Moğolistan",
"Moldova",
"Monako",
"Monserat",
"Moritanya",
"Morityus",
"Mozambik",
"Myanmar",
"Namibya",
"Nauru",
"Nepal",
"Nijer",
"Nijerya",
"Nikaragua",
"Niyu",
"Noel Adası",
"Norfolk Adası",
"Norveç",
"Orta Afrika Cumhuriyeti",
"Özbekistan",
"Pakistan",
"Palau",
"Panama",
"Papua Yeni Gine",
"Paraguay",
"Peru",
"Pitcairn Adaları",
"Polonya",
"Portekiz",
"Puerto Riko",
"Reunion",
"Romanya",
"Ruanda",
"Rusya Federasyonu",
"Samoa",
"San Marino",
"São Tomé ve Príncipe",
"Senegal",
"Seyşeller",
"Sierra Leone",
"Şili",
"Singapur",
"Sırbistan",
"Slovakya",
"Slovenya",
"Solomon Adaları",
"Somali",
"Sri Lanka",
"Sudan",
"Surinam",
"Suriye",
"Suudi Arabistan",
"Svalbard ve Jen Mayen",
"Tacikistan",
"Tanzanya",
"Tayland",
"Tayvan Cumhuriyeti",
"Timsah Adaları",
"Togo",
"Tokelau",
"Tonga",
"Trinidad ve Tobago",
"Tunus",
"Türkiye",
"Türkler ve Kayıkları Adaları",
"Türkmenistan",
"Tuvalu",
"Uganda",
"Ukrayna",
"Umman",
"Ürdün",
"Uruguay",
"Vanuatu",
"Vatikan Şehri",
"Venezuela",
"Vietnam",
"Walis ve Futuna",
"Yemen",
"Yeni Kaledonya",
"Yeni Zelanda",
"Yunanistan",
"Zambiya",
"Zimbabve"];

@mferten
Copy link

mferten commented Feb 24, 2019

OK here is the full version (all characters are checked as you did in the code)
var alfabe = "AaBbCcÇçDdEeFfGgĞğHhIıİiJjKkLlMmNnOoÖöPpQqRrSsŞşTtUuÜüVvWwXxYyZz0123456789";
function turkcesiralama(a, b) {
if (a.length === 0 || b.length === 0) {
return a.length - b.length;
}
for (var i=0; i<a.length; i++) {
var ai = alfabe.indexOf(a.substring(i,i+1));
var bi = alfabe.indexOf(b.substring(i,i+1));
if (ai !== bi) {
return ai - bi;
}
}
}

@mrtcmn
Copy link

mrtcmn commented Oct 29, 2019

When i was comparing locale, i used like this;

let _a = a.info.catName.toLocaleLowerCase('tr').slice(0, 2);
let _b = b.info.catName.toLocaleLowerCase('tr').slice(0, 2);

return _a.localeCompare(_b, 'tr', {sensitivity: 'base'});

@onur-km
Copy link

onur-km commented Oct 13, 2020

You can also try ;

arr.sort(function (a, b) {
  return a.title.localeCompare(b.title);
});

It work correctly for me ty.

@haydar-can
Copy link

haydar-can commented Apr 8, 2021

var obj = [{'placeName':'Şırnak'},{'placeName':'ŞanlıUrfa'},{'placeName':'Çorum'},{'placeName':'Çanakkale'}, {'placeName':'Antep'},{'placeName':'Ğığılca'},{'placeName':'Hatay'},{'placeName':'Trabzon'},{'placeName':'Isparta'},{'placeName':'İstanbul'},{'placeName':'Ödemiş'},{'placeName':'Çankırı'}, {'placeName':'Ceyhan'},{'placeName':'Ceylanpınar'},{'placeName':'Gaziantep'},{'placeName':'Ordu'},   {'placeName':'Sarıyer'},{'placeName':'Üsküdar'},{'placeName':'şırnak'},{'placeName':'üsküdar'}
]
/**
!	@alphabet: Sıralama kalıbı
  @dir : sıralama yönü 0 veya -1 alır. 0 [ASC], 1 [DESC]
  @caseSensitive: Büyük küçük harf duyarlılığı
*/

var alpha = function(alphabet, dir, caseSensitive){
  return function(a, b){
    var pos = 0, min = Math.min(a.length, b.length);
    dir = dir || 1;
    caseSensitive = caseSensitive || false;
    if(!caseSensitive){
      a = a.toLowerCase();
      b = b.toLowerCase();
    }
    while(a.charAt(pos) === b.charAt(pos) && pos < min){ pos++; }
    return alphabet.indexOf(a.charAt(pos)) > alphabet.indexOf(b.charAt(pos)) ? dir : -dir;
  };
};

// Yerleşim JS komutu ile sıralama. 
var c = obj.sort((a,b)=>{
	let _a = a.placeName.toLocaleLowerCase('tr');
	let _b = b.placeName.toLocaleLowerCase('tr');

	return _a.localeCompare(_b, 'tr', {sensitivity: 'base'});
})

jQuery('#app').html(JSON.stringify(c));

// alpha fonksiyonu ile sıralama. 
var d = obj.sort((a,b)=>{
	return alpha('0123456789AaBbCcÇçDdEeFfGgĞğHhIıİiJjKkLlMmNnOoÖöPpQqRrSsŞşTtUuÜüVvWwXxYyZz',-1, true)
	(a.placeName,b.placeName);
});
jQuery('#app1').html(JSON.stringify(d));

Örnek :
https://jsfiddle.net/t3huqn2r/

@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