Javascript-按id更新数组中的对象并将其移动到第一个索引

Javascript-按id更新数组中的对象并将其移动到第一个索引,javascript,performance,ecmascript-6,Javascript,Performance,Ecmascript 6,我有这个阵列: const chats = [ { id: "chat-1", msg: { text: "World", date: (a date) } }, { id: "chat-2", msg: { text: "Hello", date: (a date) } }, ]; 从数据库接收更新后,我收到以下对象: // The second chat with update data {

我有这个阵列:

const chats = [
   { id: "chat-1", msg: { text: "World", date: (a date) } },
   { id: "chat-2", msg: { text: "Hello", date: (a date) } },
];
从数据库接收更新后,我收到以下对象:

  // The second chat with update data
  { id: "chat-2", msg: { text: "Bye", date: (a date) } },
如何(使用ES6)替换原始chats数组中的chat对象并将其移动到第一个索引

目前,我正在这样做,但我正在寻找一种最快的方法(较小的O)


您可以执行以下操作:

const chats=[
{id:“chat-1”,msg:{text:“World”,日期:''}},
{id:“chat-2”,msg:{text:“Hello”,日期:''}},
];
const modifiedChat={id:“chat-2”,msg:{text:“Bye”,日期:'};
const newChats=[modifiedChat,…chats.filter(item=>item.id!==modifiedChat.id)];

console.log(newChats)您可以执行以下操作

const chats=[
{id:“chat-1”,msg:{text:“World”,日期:''}},
{id:“chat-2”,msg:{text:“Hello”,日期:''}},
];
const modifiedChat={id:“chat-2”,msg:{text:“Bye”,日期:'};
const newChats=[modifiedChat,…chats.filter(item=>item.id!==modifiedChat.id)];

console.log(newChats)您可以执行类似的操作。现在,您可以访问O(1)中的每个聊天室。

您可以执行类似的操作。您现在可以访问O(1)中的所有聊天内容。

我认为没有任何方法可以访问非O(n)的聊天内容。我认为没有任何方法可以访问非O(n)的聊天内容。
// Get the modified chat
const modifiedChat = response.data;

// Search the modified chat in the chats array by id
const chatIndex = chats.findIndex(
    (chat) => chat.id === modifiedChat.id
);

 // Finally, using spread syntax, add the updated chat to the head of our current chats array
 chats = [
    modifiedChat,
    ...chats.slice(0, chatIndex),
    ...chats.slice(chatIndex + 1),
 ];