如何使用javascript和react根据创建的日期按升序对对象数组进行排序?

如何使用javascript和react根据创建的日期按升序对对象数组进行排序?,javascript,reactjs,Javascript,Reactjs,我有如下数据 const subItems = [ { id: '1', title: 'subitem-one', status: 'new', createdAt: '2020-08-13T16:32:10.000Z', orders: [ { id: '1', title: 'subitem1-order-one',

我有如下数据

const subItems = [
    {
        id: '1',
        title: 'subitem-one',
        status: 'new',
        createdAt: '2020-08-13T16:32:10.000Z',
        orders: [
            {
                id: '1',
                title: 'subitem1-order-one',
                status: 'new',
            },
            {
                id: '2',
                title: 'subitem1-order-two',
                status: 'new',
            },
        ]
    },

    {
        id: '2',
        title: 'subitem-two',
        status: 'new',
        createdAt: '2020-08-16T12:02:06.000Z',
        orders: [
            {
                id: '2',
                title: 'subitem2-order-one',
                status: 'new',
            },
       ],
    },
]
如何使用javascript根据createdAt属性按升序对对象的子项数组进行排序

预计产量如下:

const subItems = [
    {
        id: '1',
        title: 'subitem-one',
        status: 'new',
        createdAt: '2020-08-16T16:32:10.000Z',
        orders: [
            {
                id: '1',
                title: 'subitem1-order-one',
                status: 'new',
            },
            {
                id: '2',
                title: 'subitem1-order-two',
                status: 'new',
            },
        ]
    },

    {
        id: '2',
        title: 'subitem-two',
        status: 'new',
        createdAt: '2020-08-13T12:02:06.000Z',
        orders: [
            {
                id: '2',
                title: 'subitem2-order-one',
                status: 'new',
            },
        ],
    },
]
如何基于createdAt按升序对数据进行排序。最近创建的应该是第一个。有人能帮我吗。谢谢。

subItems.sort((a,b)=>new Date(a.createdAt) - new Date(b.createdAt))
下降的

subItems.sort((a,b)=>new Date(b.createdAt) - new Date(a.createdAt))
将该函数与排序算法的回调一起使用

功能分类表(子项){
子项排序((a,b)=>{
a=(新日期(a.createdAt)).getTime();
b=(新日期(b.createdAt)).getTime();
返回b-a;
});
返回子项;
}
常量子项=[
{
id:'1',
标题:"第一分项",,
状态:'新',
创建日期:“2020-08-13T16:32:10.000Z”,
订单:[
{
id:'1',
标题:“子项1顺序一”,
状态:'新',
},
{
id:'2',
标题:“第1分项第2项”,
状态:'新',
},
]
},
{
id:'2',
标题:"第二项",,
状态:'新',
创建日期:“2020-08-16T12:02:06.000Z”,
订单:[
{
id:'2',
标题:“子项2顺序一”,
状态:'新',
}
]
},
];

console.log(sortSubItems(子项))您只需将排序函数与回调一起使用即可:

const sortedItems = subItems.sort((a,b) => b.createdAt.localeCompare(a.createdAt))