3

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.

8
  • sort accepts 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. Commented May 15, 2018 at 5:17
  • stackoverflow.com/a/23618442/2569323 Commented May 15, 2018 at 5:19
  • 3
    They're all unicode strings. Commented May 15, 2018 at 5:19
  • Do you want to have all strings that start with a non ASCII character at the beginning of the array? So also strings starting with è, à, à, ä, ... ? Commented May 15, 2018 at 5:22
  • 1
    It's still not about the wording. Commented May 15, 2018 at 5:36

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.