array.sort()来重新定位已读消息



我有一个用户对象(聊天(数组,我想将所有带有未读消息的聊天推到列表顶部的前面,而不影响其他聊天位置。

这就是我到目前为止所拥有的。每次与hasUnread进行新的聊天时,未读消息都会被推到列表的顶部,但每隔一次聊天都会被重新排列。

const singleChat = [...Object.values(singles)];
singleChat.sort((a, b) => (a.hasUnread == false ? 1 : -1));

我想这是因为我需要指定我想退出的索引和我要将其推回的索引。

我在想这样的事情:将数组元素从一个数组位置移动到另一个数组,但能够破译旧位置似乎有点令人困惑。

if (new_index >= chat.length) {
var k = new_index - chat.length + 1;
while (k--) {
chat.push(undefined);
}
}
chat.splice(new_index, 0, chat.splice(old_index, 1)[0]);

任何帮助都会很棒。

我不得不使用一个循环,它有点慢,但这很有效:

let unreadmessages = [];
for (let i = 0; i < singleChat.length; i++) {
if (singleChat[i].hasUnread === true) {
unreadmessages.push(singleChat[i]);
singleChat.splice(i, 1);
}
}
let newOrderedSingleChats = unreadmessages.concat(singleChat);

最新更新