简体   繁体   English

按日期对嵌套的对象数组进行排序

[英]Sort nested Array of objects by date

I have an array of users objects with several key value pairs, and I wanted to sort users base on createdAt that in chatInfo array我有一个包含几个键值对的用户对象数组,我想根据 chatInfo 数组中的 createdAt 对用户进行排序

[
    {
        _id: "1",
        age: "30",
        chatInfo: [
            {
                chatId: "22",
                createdAt: "2020-07-07T00:39:30.571Z",
                seen: false,
                senderEmail: "debot73186@klefv.com",
            },
        ],
    },
    {
        _id: "2",
        age: "21",
        chatInfo: [
            {
                chatId: "22",
                createdAt: "2020-07-07T20:08:33.171Z",
                seen: false,
                senderEmail: "debot73186@klefv.com",
            },
        ],
    },
];

Update更新

I tried this with underscore我用下划线试过这个

const sorting = (arr)=>  {
    for (let i = 0; i < arr.length; i++) {
        const user = arr[i];
        user.chatInfo.sort((a, b) => {
            return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
        });
    }
    return _.sortBy(arr, "chatInfo");
}

You can sort elements of JavaScript arrays using the built-in sort method.您可以使用内置排序方法对 JavaScript arrays 的元素进行排序。 In order for it to work as intended, we need to compare the the ISO timestamps by its numerical value.为了使其按预期工作,我们需要通过其数值比较 ISO 时间戳。

You can easily construct Date objects with an ISO timestamp string.您可以使用 ISO 时间戳字符串轻松构造Date对象。 Using the getTime method will return its numerical representation in milliseconds.使用getTime方法将以毫秒为单位返回其数值表示。 The milliseconds can then be compared in a basic sort function.然后可以在基本排序 function 中比较毫秒。

yourArray.sort((a, b) => {
  return new Date(a.chatInfo[0].createdAt).getTime() < new Date(b.chatInfo[0].createdAt).getTime() ? -1 : 1
});

Depending on whether you need it sorted in ascending or descending order, simply flip the comparison operator to and from < and > .根据您是否需要按升序或降序排序,只需将比较运算符翻转为<>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM