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

查看:47
本文介绍了如何按数字然后按字母顺序对对象的 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.

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) 表达式会先比较ids;只有当它们相等时,它才会比较名称(并返回比较的结果).

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天全站免登陆