我从事聊天应用程序 我有一个包含短信发送的对象数组 我必须在其中拖曳发件人“ 14”和“ 18” 对于每个发件人,我希望按时间显示最新消息 这是我的数组:
const messages = [
{message: "Hello", receiver: "6", sender: "14", time: "12:26 12/11/2019"},
{message: "help", receiver: "6", sender: "14", time: "12:22 12/11/2019"},
{message: "me", receiver: "6", sender: "18", time: "12:01 12/11/2019"},
{message: "Hii", receiver: "6", sender: "18", time: "10:10 12/11/2019"},
{message: "good ", receiver: "6", sender: "18", time: "09:13 12/11/2019"},
{message: "ok", receiver: "6", sender: "18", time: "12:26 11/11/2019"},
{message: "welcoome ", receiver: "6", sender: "14", time: "11:05 12/11/2019"}
];
我该怎么做?
这是我的代码reactjs的摘录,我在this.props.chats
的const消息摘录中工作。
function parseTime(timeStr) {
const fields = timeStr.split(":").map(parseInt);
return fields[0] * 60 + fields[1];
}
let result = this.props.chats.reduce((map, item) => {
if (!map[item.sender] || parseTime(map[item.sender].time) < parseTime(item.time)) {
map[item.sender] = item;
}
return map;
}, {});
var messageInbox = Object.values(result)
console.log("Latest messages:", messageInbox);
他没有根据温度显示最后一条消息。
答案 0 :(得分:0)
使用array.sort
:
.buttons{
display: flex;
justify-content: flex-end;
}
,然后提取最后一个值:
messages.sort( a,b => parseTime(b.time) - parseTime(a.time) );
答案 1 :(得分:0)
这里是您的答案: 我将日期和时间更改为时间戳,以便可以轻松进行比较。 https://codesandbox.io/s/naughty-mcclintock-itwnx
答案 2 :(得分:0)
您可以reduce
个项目,sort
个项目,然后获取数组的第一个元素:
const senders = messages.reduce((a, c) => {
a[c.sender] = a[c.sender] || { data:[]};
a[c.sender].data.push({ sender: c.sender, message: c.message, time: c.time});
a[c.sender].data.sort((a, b)=> new Date(b.time) - new Date(a.time))
return a;
}, {})
console.log(Object.values(senders).map(s => s.data[0]));
const messages = [
{ message: "Hello", receiver: "6", sender: "14", time: "12:26 12/11/2019" },
{ message: "help", receiver: "6", sender: "14", time: "12:22 12/11/2019" },
{ message: "me", receiver: "6", sender: "18", time: "12:01 12/11/2019" },
{ message: "Hii", receiver: "6", sender: "18", time: "10:10 12/11/2019" },
{ message: "good ", receiver: "6", sender: "18", time: "09:13 12/11/2019" },
{ message: "ok", receiver: "6", sender: "18", time: "12:26 11/11/2019" },
{ message: "welcoome ", receiver: "6", sender: "14", time: "11:05 12/11/2019" }
];
const senders = messages.reduce((a, c) => {
a[c.sender] = a[c.sender] || { data:[]};
a[c.sender].data.push({ sender: c.sender, message: c.message, time: c.time});
a[c.sender].data.sort((a, b)=> new Date(b.time) - new Date(a.time))
return a;
}, {})
console.log(Object.values(senders).map(s => s.data[0]));