gpt4 book ai didi

javascript - 如何获取集合中每个发件人的最新消息?

转载 作者:行者123 更新时间:2023-11-28 03:22:33 26 4
gpt4 key购买 nike

我有一个像这样的对象数组:

const messages = [ 
{message: "ghhhhhhhh", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "14", time: "12:56"},
{message: "ggggggghjjgcgh", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "ZCiuWczin3VuibH59MISuEqR3pc2", time: "12:45"},
{message: "good afternoon", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "ZCiuWczin3VuibH59MISuEqR3pc2", time: "12:41"},
{message: "hfdsghfdfhjo", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "ZCiuWczin3VuibH59MISuEqR3pc2", time: "12:38"},
{message: "hhhhhhhhhhhhh ", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "14", time: "11:50"}
];

我想获取每个发件人的最新消息,如下所示:

const messages = [
{message: "ghhhhhhhh", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "14", time: "12:56"},
{message: "ggggggghjjgcgh", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "ZCiuWczin3VuibH59MISuEqR3pc2", time: "12:45"}
];

如何做到这一点?

最佳答案

您可以使用 array.reduce 来实现此目的,例如:

const messages = [ {message: "ghhhhhhhh", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "14", time: "12:56"}
, {message: "ggggggghjjgcgh", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "ZCiuWczin3VuibH59MISuEqR3pc2", time: "12:45"}
, {message: "good afternoon", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "ZCiuWczin3VuibH59MISuEqR3pc2", time: "12:41"}
, {message: "hfdsghfdfhjo", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "ZCiuWczin3VuibH59MISuEqR3pc2", time: "12:38"}
, {message: "hhhhhhhhhhhhh ", receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2", sender: "14", time: "11:50"}];


function parseTime(timeStr) {
const fields = timeStr.split(":").map(parseInt);
return fields[0] * 60 + fields[1];
}

let result = messages.reduce( (map, item) => {
if (!map[item.sender] || parseTime(map[item.sender].time) < parseTime(item.time)) {
map[item.sender] = item;
}
return map;
}, {});

console.log("Latest messages:", Object.values(result));

关于javascript - 如何获取集合中每个发件人的最新消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58992891/

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