javascript排序_JavaScript排序食谱

javascript排序

Elements often need to be sorted: think of an array of game scores that need to be arranged from high to low to determine player rank. Unfortunately, the standard JavaScript sort() method has some surprising limitations: it works well with common English words, but breaks down when faced with numbers, accented characters, or words in uppercase.

元素通常需要排序:想一想要从高到低排列才能确定玩家等级的一系列游戏分数。 不幸的是,标准JavaScript sort()方法有一些令人惊讶的局限性:它可以与常见的英语单词一起很好地工作,但是当遇到数字,带重音符号的单词或大写单词时会崩溃。

按字母顺序排序 (Sorting Alphabetically)

At first blush, sorting an array alphabetically should be straightforward. In the console:

乍一看,按字母顺序对数组进行排序应该很简单。 在控制台中:

var fruit = ["butternut squash", "apricot", "cantaloupe"];
fruit.sort();

> "apricot", "butternut squash", "cantaloupe"]

However, sort() faces a problem as soon as one of the elements is capitalized:

但是,将元素之一大写后, sort()就会遇到问题:

var fruit = ["butternut squash", "apricot", "Cantalope"];
fruit.sort();

> "Cantaloupe", "apricot", "butternut squash"]

This is due to the fact that, by default, sort compares Unicode code points for characters. Unicode is the way all modern computers think of characters as organized into a structured table in which each character has a unique entry code. For example, the character a has an entry of U+0061, while the code for C is U+0043 which comes before a in the Unicode table.

这是由于以下事实:默认情况下, sort比较Unicode代码点的字符。 Unicode是所有现代计算机将字符视为组织成结构化表的方式,其中每个字符都有唯一的输入代码。 例如,字符a的条目为U+0061 ,而C的代码为U+0043 ,它 Unicode表中位于a 之前

To sort an array that could contain mixed-case first letters, you either need to convert all the elements temporarily to lowercase, or sort() them using localeCompare and some arguments. It’s usually best to create this as a function for reusability:

要对可能包含首字母大写混合的数组进行排序,您需要将所有元素临时转换为小写,或者使用localeCompare和一些参数sort()它们进行sort() 。 通常最好将其创建为可重用性的函数

function alphaSort(arr) {
    arr.sort(function (a, b) {
        return a.localeCompare(b, 'en', {'sensitivity': 'base'});
    });
}

var fruit = ["butternut squash", "apricot", "Cantaloupe"];
alphaSort(fruit)

> ["apricot", "butternut squash", "Cantaloupe"]

If you want a reverse alphabetical sort, exchange the positions of a and b in the function:

如果要反向字母排序,请交换函数中ab的位置:

function alphaSort(arr) {
    arr.sort(function (a, b) {
        return b.localeCompare(a, 'en', {'sensitivity': 'base'});
    });
}

This also takes into account accented characters.

这也考虑了重音字符。

Note that localeCompare used with arguments as we have it here is only supported in IE11 and above; for older versions of IE, you’ll want to use it without arguments, and with lowercase:

请注意,只有在IE11及更高版本中才支持将localeCompare与参数一起使用。 对于较旧版本的IE,您需要不带参数且使用lowercase使用它:

function caseSort(arr) {
    arr.sort(function (a, b) {
        return a.toLowerCase().localeCompare(b.toLowerCase());
    });
}

数值排序 (Numerical Sort)

This doesn’t address the scenario given at the start of this article: sorting a series of high scores. With some arrays of numbers, sort works just fine, but with others it has an unpredictable response:

这不能解决本文开头给出的情况:对一系列高分进行排序。 对于某些数字数组, sort工作正常,但对于其他一些数组,其响应却无法预测:

var highScores = [11, 57, 10, 16, 32, 100];
highScores.sort();

> [10, 100, 11, 16, 32, 57]

This response is due to the fact that sort() is doing a lexicographical comparison: it is converting the numbers into strings, and comparing the Unicode code points for the characters. Achieving a true numerical sort involves adding a compare function. This one is small enough that you may want to add it directly to sort itself:

该响应是由于sort()进行了字典上的比较:将数字转换为字符串,并比较字符的Unicode代码点。 实现真正的数值排序涉及添加比较函数。 这个很小,您可能想要直接添加它以对其进行sort

highScores.sort( function(a,b) { return a - b; } ); 
> [10, 11, 16, 32, 57, 100]

Again, to sort the numbers in reverse order, exchange the placement of a and b in the function.

同样,要以相反的顺序对数字进行排序,请交换函数中ab的位置。

排序JSON (Sorting JSON)

If we have a JSON array of high scores:

如果我们有一个高分的JSON数组

var scores = [
  {
    "name": "Daniel",
    "score": 21768
  },
  {
    "name": "Michael",
    "score": 33579
  },
  {
    "name": "Alison",
    "score": 38395
  }
];

In JavaScript 2015, you can use:

在JavaScript 2015中,您可以使用:

scores.sort((a, b) => b.score - a.score));

For browsers without support (and sorting from lowest to highest, just to show the variation):

对于不支持的浏览器(为了显示变化而从最低到最高排序):

scores.sort(function(a, b) { return a.score - b.score })

结论 (Conclusion)

Sorting in JavaScript is perhaps a little less straightforward than one might hope, but it’s my hope that these recipes will make the job a little easier.

用JavaScript排序可能比人们希望的要简单一些,但是我希望这些食谱能使工作变得容易一些。

Finding unique elements in arrays is a related and useful, but one that I’ll address in a separate article.

在数组中查找唯一元素是相关且有用的,但是我将在另一篇文章中介绍。

翻译自: https://thenewcode.com/1125/JavaScript-Sorting-Recipes

javascript排序

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值