Javascript ES6自定义排序方法并非始终有效 [英] Javascript ES6 custom sort method not working all the times

查看:663
本文介绍了Javascript ES6自定义排序方法并非始终有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对我的JSON输出进行排序.

I want to sort my JSON output.

我为此创建了自己的排序方法,如您在此处看到的:

I made my own sort method for it as you can see here:

const sortAsc = (propertyName) => (a, b) => a[propertyName] === b[propertyName] ? 0 : a[propertyName] < b[propertyName] ? -1 : 1;
const sortDesc = (propertyName) => (a, b) => a[propertyName] === b[propertyName] ? 0 : a[propertyName] < b[propertyName] ? 1 : -1;

我这样称呼它:

asc(value) {
    this.result.sort(this.sortAsc(value));
}

它可以工作,但是当我对其进行排序时,并不能总是正确排序.

It works sort of but when I sort it it doesn't sort right always.

看看这个小gif: https://gyazo.com/5f590f7c921eb1cb3bc4138f85c2162b

Take a look at this little gif: https://gyazo.com/5f590f7c921eb1cb3bc4138f85c2162b

如您所见,它实际上不适用于该ID.它在Naam上(荷兰语中的名称)升序工作,但是在降序时,它首先给出2个以v&开头的名称. k.为什么会这样?

As you see it doesn't really work with the ID. It works ascending on Naam (name in dutch) But when descending it first gives 2 names starting with v & k. Why is that?

好吧,如果那是很难解决的问题,那实际上不是问题.只要它可以对数字和字符串进行排序.

Well, If that's something what is hard to be fixed it isn't really a problem. As long it can sort numbers aswell as strings.

要注意的另一件事是我正在使用Angular 4.4.4.我用谷歌搜索了一个内置的sort/orderBy函数,但是发现它不是内置的.但是,如果我可以使用Angular提供的任何功能来简化它,我将很乐意使用它!

One more thing to note is that I am using Angular 4.4.4. I googled for a build-in sort/orderBy function but found that's not build-in. But if there is anything I can use that Angular provides to make it easier I would be happy to use it!

我的新方法:

sortAsc = (propertyName) => (a, b) => a[propertyName].localeCompare(b[propertyName]);

推荐答案

您可以使用

You could use String#localeCompare with option:

localeCompare() 方法返回一个数字,该数字指示参考字符串是按排序顺序位于给定字符串之前还是之后还是与给定字符串相同.

The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

新的localesoptions参数使应用程序可以指定应使用其排序顺序的语言,并自定义函数的行为.在较早的实现中,忽略了localesoptions参数,使用的语言环境和排序顺序完全取决于实现.

The new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation dependent.

const sortAsc = propertyName => (a, b) =>
    a[propertyName].localeCompare(b[propertyName], undefined, { numeric: true, sensitivity: 'base' });


const sortDesc = (propertyName) => (a, b) =>
    -a[propertyName].localeCompare(b[propertyName], undefined, { numeric: true, sensitivity: 'base' });

这篇关于Javascript ES6自定义排序方法并非始终有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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