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

编程入门 行业动态 更新时间:2024-10-24 12:20:29
本文介绍了按自定义字母顺序对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

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

本文发布于:2023-11-30 00:54:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648185.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   数组   字母   顺序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!