如何按字母顺序对javascript数组进行排序,然后按字母顺序排序? [英] How can I sort a javascript array of objects numerically and then alphabetically?

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

问题描述


可能重复:

通过JavaScript中的字段值对数组中的对象进行排序

如何按字母顺序(按ID)按字母顺序(按名称)对对象数组进行排序?

How can I sort an array of objects numerically (by id) then alphabetically (by name)?

当前方式是提供无效输出。

The current way is providing invalid output.

这是我试图排序的对象

var items = [
    {
        "id": 165,
        "name": "a"
    },
    {
        "id": 236,
        "name": "c"
    },
    {
        "id": 376,
        "name": "b"
    },
    {
        "id": 253,
        "name": "f"
    },
    {
        "id": 235,
        "name": "e"
    },
    {
        "id": 24,
        "name": "d"
    },
    {
        "id": 26,
        "name": "d"
    }
]

和我试图排序的方式

items.sort(function(a, b) {
    return (a.id - b.id);
}).sort(function(a, b) {
    return (a.name - b.name);
});

这里是jsfiddle。

here is the jsfiddle.

< a href =http://jsfiddle.net/jh4xb/ =noreferrer> http://jsfiddle.net/jh4xb/

编辑:对不起,我已经对这个问题感到困惑了一段时间。

Sorry for the confusion, I've been so confused by this problem for a while.

我想要完成的是先排序最高的id ,然后按字母顺序排序,最后看起来像:

What I'm trying to accomplish is to sort by the highest id first, and then sort alphabetically so in the end it should look like:

var items = [
    {
        "id": 376,
        "name": "b"
    },
    {
        "id": 253,
        "name": "f"
    },
    {
        "id": 236,
        "name": "c"
    },
    {
        "id": 235,
        "name": "e"
    },
    {
        "id": 165,
        "name": "a"
    },
    {
        "id": 26,
        "name": "d"
    },
    {
        "id": 24,
        "name": "d"
    }
]


解决方案

我认为最好只用... ...

I think it's better done just with...

items.sort(function(a, b) { 
  return a.id - b.id  ||  a.name.localeCompare(b.name);
});

第二种基本上会否定第一种,所以你必须做一次。 )

The second sort will basically negate the first one, so you have to do it once. )

a.id - b.id || a.name.localeCompare(b.name)表达式将首先比较 id s;只有它们相等,它才会比较名称(并返回此比较的结果)。

a.id - b.id || a.name.localeCompare(b.name) expression will first compare the ids; only if they are equal, it will compare the names (and return the result of this comparison).

如果您需要撤销订单,请交换头寸( b.id - a.id 等。 ) - 或者只是否定整个事情:

If you need to reverse the ordering, swap the positions (b.id - a.id, etc.) - or just negate the whole thing:

items.sort(function(a, b) { 
  return - ( a.id - b.id  ||  a.name.localeCompare(b.name) );
});

这是 JSFiddle (必须简化数据以显示我的观点)。

Here's the JSFiddle (have to simplify the data a bit to show my point).

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

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