gpt4 book ai didi

javascript - 按属性对三个不同的对象数组进行排序

转载 作者:数据小太阳 更新时间:2023-10-29 06:04:05 24 4
gpt4 key购买 nike

我有三个不同的对象数组,我需要对 Date 字段进行排序,其中每个组中的字段具有不同的名称。

下面是我的数据示例:

const documents = [
{
documentId: 'ADB0125A',
fileName: 'test_2018.pdf',
date': '2017-12-02T19:08:52+01:00' // Field to sort by
},
{
documentId: '123456',
fileName: 'test2_2018.pdf',
date': '2017-12-12T22:08:52+01:00' // Field to sort by
},
{
documentId: '121212',
fileName: 'test3_2018.pdf',
date': '2018-05-22T23:08:52+01:00' // Field to sort by
}];

const conversations = [
{
conversationId: '1102',
lastUpdate: '2015-10-10T18:19:12+01:00' // Field to sort by
},
{
conversationId: '5622',
lastUpdate: '2019-08-16T18:19:12+01:00' // Field to sort by
},
{
conversationId: '112',
lastUpdate: '2015-10-26T18:19:12+01:00' // Field to sort by
}];

const invoices = [
{
invoiceId: "20100392077",
rechnungsDatum: "2019-02-10" // Field to sort by
},
{
invoiceId: "5550392077",
rechnungsDatum: "2018-02-05" // Field to sort by
},
{
invoiceId: "3336392077",
rechnungsDatum: "2018-12-11" // Field to sort by
}];

目标: 返回最新的 4 个结果(一旦我列出了最终结果集 ASC,我可以使用 .reverse() 获得), 与它们的来源无关。我希望得到:

const result = [
{
conversationId: '5622',
lastUpdate: '2019-08-16T18:19:12+01:00'
},
{
invoiceId: "20100392077",
rechnungsDatum: "2019-02-10"
},
{
invoiceId: "3336392077",
rechnungsDatum: "2018-12-11"
},
{
documentId: '121212',
fileName: 'test3_2018.pdf',
date': '2018-05-22T23:08:52+01:00'
}
]

是否可以对所有三个对象使用独特的Array.sort 方法,或者唯一的方法是成对比较它们并根据部分结果构建结果?

最佳答案

您可以获取一个对象,其中包含所需日期属性的替换键和一个保留源和规范化日期属性的平面数组,对数组进行排序并取回前四个元素。

最后删除不必要的信息并检索原始对象结构。

const
documents = [{ documentId: 'ADB0125A', fileName: 'test_2018.pdf', date: '2017-12-02T19:08:52+01:00' }, { documentId: '123456', fileName: 'test2_2018.pdf', date: '2017-12-12T22:08:52+01:00' }, { documentId: '121212', fileName: 'test3_2018.pdf', date: '2018-05-22T23:08:52+01:00' }],
conversations = [{ conversationId: '1102', lastUpdate: '2015-10-10T18:19:12+01:00' }, { conversationId: '5622', lastUpdate: '2019-08-16T18:19:12+01:00' }, { conversationId: '112', lastUpdate: '2015-10-26T18:19:12+01:00' }],
invoices = [{ invoiceId: "20100392077", rechnungsDatum: "2019-02-10" }, { invoiceId: "5550392077", rechnungsDatum: "2018-02-05" }, { invoiceId: "3336392077", rechnungsDatum: "2018-12-11" }]
keys = { documents: 'date', conversations: 'lastUpdate', invoices: 'rechnungsDatum' },
result = Object
.entries({ documents, conversations, invoices })
.reduce((r, [k, v]) => [...r, ...v.map(payload => ({ payload, date: payload[keys[k]] }))], [])
.sort((a, b) => b.date.localeCompare(a.date))
.slice(0, 4)
.map(({ payload }) => payload);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 按属性对三个不同的对象数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56147924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com