Almaszosz
Almaszosz

Reputation: 50

TypeScript Array.splice deleting wrong entry

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!

Upvotes: 0

Views: 49

Answers (2)

Mulan
Mulan

Reputation: 135287

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

Upvotes: 1

Matthieu Riegler
Matthieu Riegler

Reputation: 55197

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

Upvotes: 1

Related Questions