How to sort user names that are in multiple languages by specific languages order in javascript?
I have user names that are in multiple languages, and I have to sort the names by the 'Korean → English → And other languages in unicode' order. And additionally, when they are in same languages, I have to sort based on the order they are specified in the unicode as well.
So for example, if first user name is in Korean and second user name is in English, first user comes before second user. And another example, if first user name is English and second user name is also in English, I have to sort this as well.
I made functions that checks if they are in specific languages.
isKorean
checks for if it's in Korean, isEnglish
is checks English, and if it's not both, it will be other languages.
const isKorean = (str) => {
const regExp = /^[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]*$/;
if (regExp.test(str)) {
return true;
}
return false;
};
const isEnglish = (str) => {
const regExp = /^[a-zA-Z]*$/;
if (regExp.test(str)) {
return true;
}
return false;
};
However these are my problems.
- I do not know how to sort user names even I know what languages they are in
- I do not know how to sort user names even when they are in same languages.
So my question is...
- How do you sort user names in Korean → English → Other languages order after checking what language they are in?
-
And once first one is resolved, how do I sort user names that are in same languages?
- user names in Korean
- user names in English
- user names in other languages
Thanks in advance.
I would first separate out the list into three lists: Korean, English, Other, then sort each one, and then concatenate them. JS Array Sort doesn't have a built-in way to do multi-faceted sorting (also known as "group by" sorting)
note: I'm not handling when a name matches both Korean and English here
const isKorean = (str) => {
const regExp = /^[ㄱ-ㅎ|ㅏ-ㅣ|가-힣]*$/;
if (regExp.test(str)) {
return true;
}
return false;
};
const isEnglish = (str) => {
const regExp = /^[a-zA-Z]*$/;
if (regExp.test(str)) {
return true;
}
return false;
};
const names = ['무현', 'Mark', 'Шумело', 'Brad', '규영', 'Tom', 'Consuela', '차빈', '규영', '차빈', '시훈', 'Ярослав', ];
const korean = names.filter(isKorean).sort();
const english = names.filter(isEnglish).sort();
const other = names.filter((n) => !isKorean(n) && !isEnglish(n)).sort();
const sorted = [...korean, ...english, ...other];
console.log(sorted);
/*
[
"규영",
"규영",
"무현",
"시훈",
"차빈",
"차빈",
"Brad",
"Consuela",
"Mark",
"Tom",
"Шумело",
"Ярослав"
]*/