Skip to content

Instantly share code, notes, and snippets.

@rthor
Last active April 26, 2017 08:59
Show Gist options
  • Save rthor/8370895 to your computer and use it in GitHub Desktop.
Save rthor/8370895 to your computer and use it in GitHub Desktop.
Sort algorithm for Icelandic characters and other special characters.

Usage

Create some array:

var names = [
  'Jón Margeir Jónson',
  'Fríður',
  'Ægir',
  'Friðgeir',
  'Ásmundur',
  '.DS_Store',
  'Élgraður',
  'Sólmundur',
  'Aron Ómarsson',
  'Aron Omarsson'
];

Sort the thing:

names = names.sort( international() );

Now the array is sorted as follows:

[
  '.DS_Store',
  'Aron Omarsson',
  'Aron Ómarsson',
  'Ásmundur',
  'Élgraður',
  'Friðgeir',
  'Fríður',
  'Jón Margeir Jónson',
  'Sólmundur',
  'Ægir'
]
function groperty ( obj, propList ) {
if ( typeof obj !== 'object' ) return obj;
if( Object.prototype.toString.call( propList ) !== '[object Array]' ) {
propList = propList.replace(/^\./, '').replace(/\.$/, '').split('.');
}
propList.forEach(function walkThroughObj ( propName ) {
obj = obj[ propName ] ? obj[ propName ] : obj;
});
return obj;
}
function international ( propList ) {
var alphabet = '._!*@()[]{}#^&%-=+01234567989aāáǎàâãąbcćčçdďðeēéěèêëęfgğhıiīíǐìîïjklłmnńňñoōóǒòôpqrřsśšştťuūúǔùůûüǖǘǚǜvwxyýzźżžþæœøõåäö'
, firstA
, firstB;
return function(a, b) {
if ( propList ) {
a = groperty(a, propList);
b = groperty(b, propList);
}
a = a.toLowerCase();
b = b.toLowerCase();
firstA = alphabet.indexOf(a[0]);
firstB = alphabet.indexOf(b[0]);
return firstA === firstB ? a === b ? 0 : a < b ? -1 : 1 : firstA - firstB;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment