使用特殊字符在 Javascript 中排序 [英] Sorting in Javascript with special characters

查看:27
本文介绍了使用特殊字符在 Javascript 中排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含以下值的数组

I have an array with the following values

asd sdf dsdf 1sadf *sdf !sdf @asdf _asd .sadf (sadf )sadf #sadf 
^asdf &asdf %asdf -sadf =sadf +sadf -sdf

我想按照以下方式在javascript中将其分为三个部分.

and i want to sort it in javascript in the following way in to three parts.

  1. 以特殊字符开头的单词
  2. 从数字开始的单词
  3. 以字母开头的单词.

所以这应该是有序数组的序列.

So this should be the sequence of the sorted array.

编辑:这是我一直在试验的一个函数:

EDIT: Here's a function that I've been experimenting with:

function naturalSort(a, b) {
   a = a.path.toLowerCase();
   b = b.path.toLowerCase();
   var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
  sre = /(^[ ]*|[ ]*|[_]*$)/g,
  dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
  hre = /^0x[0-9a-f]+$/i,
  ore = /^0/,
   // convert all to strings and trim()
  x = a.toString().replace(sre, '') || '',
  y = b.toString().replace(sre, '') || '',
   // chunk/tokenize
  xN = x.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'),
  yN = y.replace(re, '\0$1\0').replace(/\0$/, '').replace(/^\0/, '').split('\0'),
   // numeric, hex or date detection
  xD = parseInt(x.match(hre)) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
  yD = parseInt(y.match(hre)) || xD && y.match(dre) && Date.parse(y) || null;
   // first try and sort Hex codes or Dates
   if (yD)
    if (xD < yD) return -1;
    else if (xD > yD) return 1;
   // natural sorting through split numeric strings and default strings
   for (var cLoc = 0, numS = Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
    // find floats not starting with '0', string or 0 if not defined (Clint Priest)
    oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
    oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
    // handle numeric vs string comparison - number < string - (Kyle Adams)
    if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? -1 : 1;
    // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
    else if (typeof oFxNcL !== typeof oFyNcL) {
     oFxNcL += '';
     oFyNcL += '';
    }
    if (oFxNcL <= oFyNcL) return -1;
    if (oFxNcL >= oFyNcL) return 1;
   }
   return 0;
  }

推荐答案

老实说,我完全不知道你发布的函数是做什么的.......

To be honest, I have no idea what your posted function does ... at all.

以下方法使用位置出现比较字符串的第一个字符.具有相同首字符的字符串会定期排序.

The following approach compares strings on their first character, using positional occurrence. Strings with the same first character are sorted regularly.

顺便说一句,没有测试空字符串.

Btw, didn't test for empty strings.

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

        if (index_a === index_b) {
            // same first character, sort regular
            if (a < b) {
                return -1;
            } else if (a > b) {
                return 1;
            }
            return 0;
        } else {
            return index_a - index_b;
        }
    }
}

var items = ['asd','sdf', 'dsdf', '1sadf', '*sdf', '!sdf', '@asdf', '_asd', '.sadf', '(sadf', ')sadf', '#sadf', '^asdf', '&asdf', '%asdf', '-sadf', '=sadf', '+sadf', '-sdf', 'sef'],
sorter = MySort('*!@_.()#^&%-=+01234567989abcdefghijklmnopqrstuvwxyz');

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

输出:

["*sdf", "!sdf", "@asdf", "_asd", ".sadf", "(sadf", ")sadf", "#sadf", "^asdf", 
 "&asdf", "%asdf", "-sadf", "-sdf", "=sadf", "+sadf", "1sadf", 
 "asd", "dsdf", "sdf", "sef"]

这篇关于使用特殊字符在 Javascript 中排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆