Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Sort mixed array of ASCII string and non-ASCII strings

Tags:

javascript

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.

like image 431
rendom Avatar asked Feb 17 '26 15:02

rendom


1 Answers

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);
like image 96
CertainPerformance Avatar answered Feb 20 '26 03:02

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!