作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个像这样的对象数组:
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/
我是一名优秀的程序员,十分优秀!