rendom
rendom

Reputation: 3705

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

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.

Upvotes: 3

Views: 1918

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

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);

Upvotes: 3

Related Questions