8 Lip 2014

Sortowanie polskich znaków w javascript

function MySort(alphabet) {
  return function (a, b) {
    const index_a = alphabet.indexOf(a[0]);
    const index_b = alphabet.indexOf(b[0]);

    if (index_a === index_b) {
      if (a < b) {
        return -1;
      }
      if (a > b) {
        return 1;
      }
      return 0;
    }
    return index_a - index_b;
  };
}

const items = [
  'świat',
  'ł',
  'k',
  'ą',
  '*sdf',
  '!sdf',
  '@asdf',
  '_asd',
  '.sadf',
  '(sadf',
  ')sadf',
  '#sadf',
  '^asdf',
  '&asdf',
  '%asdf',
  '-sadf',
  '=sadf',
  '+sadf',
  '-sdf',
  'sef',
];
const sorter = MySort(
  '*!@_.()#^&%-=+01234567989aąbcćdeęfghijklłmnńoóprsśtuwyzźż'
);

console.log(items.sort(sorter));