Search code examples
javascriptreact-nativesortingsplitsplice

array.sort() to reposition a read message


I have an array of objects (chats) for a user and I want to push all chats with unread messages to the front of the top of the list without effecting the rest of the chats positions.

This is what I have so far. Every time a new chat with hasUnread comes through the unread message is pushed to the top of the list but every other chat is rearranged.

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

I think it is because I need to specify the index I want to pull out and the index I was to push it back into.

I was thinking of something like this: Move an array element from one array position to another but it seems a bit confusing to be able to decipher the old position.

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]);

any help would be great.


Solution

  • I had to use a loop and it's kind of slow but this works:

    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);