javascript - 对对象数组和这些对象中的嵌套数组进行排序

标签 javascript arrays sorting

更新示例,因为它与帖子中给出的对象结构不匹配

有一个数组,里面有多个这样的对象:

{ 
    text: text,
    elements: [
        { 
            id: id, 
            page: pageNumber 
        }
    ]
}

现在我需要用两种方式对内容进行排序:

  1. 文本字段对所有数组元素进行排序

我会这样做:

array.sort(function(a,b) {
    if (a.text < b.text) return -1;
    if (a.text > b.text) return 1;
    return 0;
});
  1. 嵌套的 elements 数组的内容也应该按 page 字段排序。

我不知道如何对嵌套在对象中的数组进行排序...不幸的是,它变得更加困难,因为元素是字符串,但代表一些页码。那么我怎样才能以正确的方式对这些数据进行排序,因为元素可能看起来像 12323-34?在 123-12523-34 的情况下,最后一个元素应该是第一个。

示例

[
    {   
        text: 'Some text',
        elements: [
            { id: 1, pages: '45-67' },
            { id: 2, pages: '12-34' }
        ]

    },
    {
        text: 'Another text',
        elements: [
            { id: 3, pages: '12-34' }
        ]
    }
]

应排序为:

[
    {
        text: 'Another text',
        elements: [
            { id: 3, pages: '12-34' }
        ]
    },
    {   
        text: 'Some text',
        elements: [
            { id: 2, pages: '12-34' },
            { id: 1, pages: '45-67' }
        ]

    },
]

因此对象顺序发生了变化,因为 AS 之前,并且(现在)第二个对象中的页面元素顺序相反。

最佳答案

对于第一部分,您可以使用 String#localeCompare 的力量.并为页面数组使用另一个排序函数来拆分字符串。

var array = [{ id: 1, text: 'Some text', elements: [{ id: 1, pages: '45-67' }, { id: 2, pages: '12-34' }, { id: 4, pages: '12-5' }, { id: 5, pages: '12' }] }, { id: 3, text: 'Another text', elements: [{ id: 3, pages: '12-34' }] }];

array.sort(function (a, b) {
    return a.text.localeCompare(b.text);
});

array.forEach(function (el) {
    el.elements.sort(function (a, b) {
        var aa = a.pages.split('-'),
            bb = b.pages.split('-');
        return aa[0] - bb[0] || (aa[1] || 0) - (bb[1] || 0);
    });
});
    
console.log(array);

关于javascript - 对对象数组和这些对象中的嵌套数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38351182/

相关文章:

javascript - 将关联帐户的 Stripe 费用 ID 和帐户 ID 公开给客户端是否安全?

SD 卡中的 Blackberry BitmapField

javascript - react map 函数: how to output content of all nested arrays at once?

c# - 将数据收集到一个对象中并在 .NET/C# 中对其进行排序

javascript - jsGrid 中的自动调整列大小

javascript - 第一个编程游戏的问题(javascript/jQuery)

javascript - 如何在搜索栏中附加href以选择下拉列表中的选项?

javascript - 如何删除数组中匹配的元素

ruby - 如何在 Ruby 中执行复杂的自定义排序?

python - Python 中字符串的基数排序