按自定义字母顺序对数组进行排序

时间:2015-11-12 14:41:28

标签: javascript

如何对这样的数组进行排序:

['apple','very','auto','tom','tim','violet'....]

按v,a,t,x,b ......等排序(不是alphebetical)

['violet','very','auto','tom','tim',...]

在剧本中,我会做这样的事情:

myArray.sort('v','a','t'...)

我如何在JavaScript中完成?

2 个答案:

答案 0 :(得分:5)

您可以使用此数组中第一个字母的索引维护字母优先级和sort的数组。

此版本将 not 的所有输入以排序数组末尾的一个有序字符开头,以常规(区域设置敏感)字母顺序排列:

var order = ['v','a','t'];
var input = ['violet', 'EXTRA 2', 'very','auto','tom','tim', 'EXTRA 1'];
input.sort(function(a, b) {
  // are the strings equal?
  if(a === b) {
    return 0;
  }

  // if they are not equal, compare the first letters
  //  against the custom sort order
  var indexOfA = order.indexOf(a[0]);
  var aInList = indexOfA >= 0;

  var indexOfB = order.indexOf(b[0]);
  var bInList = indexOfB >= 0;

  // if the first letter of neither string is in the list,
  //  compare alphabetically
  if(!aInList && !bInList) {
    return a.localeCompare(b);
  } else if(!aInList) {
    // the first letter of only a is not in the list
    return 1;
  } else if(!bInList) { 
    // the first letter of only b is not in the list
    return -1;
  } else if(indexOfA === indexOfB) {
    // the first letter of a and b are both in the list
    //  and they are the same
    return a.localeCompare(b);
  } else {
    // the first letters are different; sort by first letter
    return indexOfA - indexOfB;
  }
})

如果您可以保证第一个字母在排序顺序数组中,则可以省略if(indexOfX === -1)个检查。

答案 1 :(得分:0)

我不擅长js它可能会进一步优化,但这必须适合你。

var outArray = new Array();
var inArray = [ "Zpple", "Zuto", "tim", "tom", "very", "tiolet", "Ztest" ];


inArray.forEach(function(input, i){

    outArray.push(input);
    delete inArray[i];

    var startChar = input.charAt(0);

    inArray.forEach(function(input, i){

        if(input.startsWith(startChar)){
            outArray.push(input);
            delete inArray[i];      
        }       

    });


});

输出:

   ["Zpple", "Zuto", "Ztest", "tim", "tom", "tiolet", "very"]