3 回答
TA贡献1866条经验 获得超5个赞
您可以为此目的使用 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));
TA贡献1805条经验 获得超10个赞
你可以这样做: -
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 getUniqueMessages = (messages) => {
const msgMap = {};
const uniqueMsg = [];
messages.forEach(item => {
if(!msgMap[item.sender]) {
msgMap[item.sender] = true;
uniqueMsg.push(item)
}
});
return uniqueMsg;
}
// console.log(getUniqueMessages(messages));
TA贡献1859条经验 获得超6个赞
const result = [];
const map = new Map();
for (const item of messages) {
if(!map.has(item.sender)){
map.set(item.sender, true);
result.push({
message: item.message,
reciever: item.reciever
sender: item.sender,
time: item.time
});
}
}
console.log(result)
添加回答
举报