按自定义字母顺序对数组进行排序 [英] Sort an array in custom alphabetical order

查看:213
本文介绍了按自定义字母顺序对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do you sort an array like this:

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

要按v订购,a,t,x,b ....等(不是alphebetical)

To get it ordered by v,a,t,x,b....etc (Not alphebetical)

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

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

In script, I'd do something like this:

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

我如何在JavaScript中完成?

How can I do it in JavaScript?

推荐答案

您可以维护一个字母优先级的数组和按此数组中第一个字母的索引排序

You could maintain an array of the letter precedence and sort by the index of the first letter in this array.

这个版本将任何 not 的输入开头,在排序数组的末尾以一个有序字符开头,常规(语言环境 - 敏感的)字母顺序:

This version puts any inputs that do not start with one of your ordered characters at the end of the sorted array, in regular (locale-sensitive) alphabetical order:

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)检查。

If you can guarantee that the first letter is in your sort order array, you can omit the if(indexOfX === -1) checks.

这篇关于按自定义字母顺序对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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