For example I have an array
let fruits = ["apple", "яблоко", "grape"]
When I do
let result = fruits.sort()
Result will be
["apple", "grape", "яблоко"]
But I want unicode items to be at the start of result array.
You can check to see if the string starts with a word character in the sort function:
const fruits = ["apple", "яблоко", "grape"];
const isAlphabetical = str => /^\w/.test(str);
fruits.sort((a, b) => (
isAlphabetical(a) - isAlphabetical(b)
|| a.localeCompare(b)
))
console.log(fruits);
A more robust sorting function would check each character against each other character:
const fruits = ["apple", "яблоко", "grape", 'dog', 'foo', 'bar', 'локоfoo', 'fooлоко', 'foobar'];
const isAlphabetical = str => /^\w/.test(str);
const codePointValue = char => {
const codePoint = char.codePointAt(0);
return codePoint < 128 ? codePoint + 100000 : codePoint;
};
fruits.sort((a, b) => {
for (let i = 0; i < a.length; i++) {
if (i >= b.length) return false;
const compare = codePointValue(a[i]) - codePointValue(b[i]);
if (compare !== 0) return compare;
}
return true;
})
console.log(fruits);
sortaccepts a callback with that you can define how the sorting should happen. If you are not able to get it work with you custom callback, then show that callback and explain what incorrect result you get.è,à,à,ä, ... ?