Home > Blockchain >  TypeScript Array.splice deleting wrong entry
TypeScript Array.splice deleting wrong entry

Time:01-06

So, i have an array with messages: Example:

author: "63aea86fe37c6b1242a6970a"
chatid: "63aea8c5e37c6b1242a6973f"
files: Array [ "http://localhost:3000/CDN/attachments/63aea8c5e37c6b1242a697…37c6b1242a6970a/20230105124217/photo_2022-11-10_19-02-43.jpg" ]
message: "message"
msgid: "63b6c5a9848cd21d81863f95"
pfp: "http://localhost:3000/CDN/pfp/default.png"
sent_at: "Thu Jan 05 2023 13:42:17 GMT 0100 (közép-európai téli idő)"
username: "Alms"

And when i use messages (the array's name).find :

let foundMsg = await this.messages.find((msg: any) => msg.msgid === msgid);

Then i delete the found message with splice:

this.messages.splice(foundMsg, 1);

Then it always removes the first entry of the array. Can you tell me why? Thanks!

CodePudding user response:

find will return the element, not the index. Use findIndex instead, but don't forget to check for the not-found index, -1 -

const index = this.messages.findIndex(m => m.msgid == msgid)
if (index != -1)
  this.messages.splice(index, 1)

If you fail to do this check, splice will remove the last element from the array in the event the msgid is not found.

Note find and findIndex are synchronous so you do not need to await

CodePudding user response:

splice takes an index, don't use find() but findIndex().

  • Related