0

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.

Dennis Hackethal
  • 13,662
  • 12
  • 66
  • 115
Olivia
  • 1,843
  • 3
  • 27
  • 48
  • What do you mean by "it seems a bit confusing to be able to decipher the old position"? – Dennis Hackethal Oct 02 '20 at 21:30
  • @weltschmerz how do I find the old index when I don't know where in the array the item lies? I suppose I could loop through the singleChat object and look for "hasUnread" and if it does then take that index and save it to a map and then keep looping to look for the next chat that has an unread message but this seems like it would be super time consuming and unnecessary – Olivia Oct 05 '20 at 16:34
  • 1
    A bit distracted right now but yes if you’re stuck with an array loop seems to be the only way. If you’re not stuck with arrays use a more performance data structure. – Dennis Hackethal Oct 05 '20 at 21:43

1 Answers1

0

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);
Olivia
  • 1,843
  • 3
  • 27
  • 48