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

问题描述

嘿朋友,我有一个具有以下值的数组

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


我想按以下方式用javascript分为三个部分.

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

因此,这应该是排序数组的顺序..

请帮帮我.. !!

Hey friends 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


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

1) word starting from special character
2) word starting from digit
3) word starting from alphabets.

So this should be the sequence of the sorted array..

Please help me out..!

推荐答案

function sortFunction(a, b) {
  // your array elements will be passed to this function as a, b
  // TODO:
  //   compare a to b
  //   if a should come before b, return -1
  //   if a should come after b, return 1
  //   if a and b should be considered equal, return 0
  return 0;
}

var myarray = ['asd', 'sdf', ..., '-sdf'];
myarray.sort(sortFunction);



注意:在Google中搜索"javascript数组排序",找到了 [ ^ ]作为第一个结果.



Note: Searched Google for "javascript array sorting", found this[^] as the first result.


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


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

10-29 14:30