Home > Back-end >  JS array splice deleting first element
JS array splice deleting first element

Time:01-23

So, i have an array of pfps:

["63c959f37337160e2de8b7e4/20230122173537/profilepicture.png","63c959f37337160e2de8b7e4/20230122173616/profilepicture.png"]

And, i want to remove "63c959f37337160e2de8b7e4/20230122173616/profilepicture.png" from the list.

But when i run this code:

let foundPfp = await pfps.find((pfp: any) => pfp === data.pfpId)
if (foundPfp != -1)
   pfps.splice(foundPfp, 1)

then it removes "63c959f37337160e2de8b7e4/20230122173537/profilepicture.png"

Can you tell me why? Thanks!

CodePudding user response:

Array.prototype.find() returns the element itself. Array.prototype.splice() expects an index as first parameter. You should use Array.prototype.findIndex() instead.

CodePudding user response:

Not sure if this helps, but...

Removing the first element from an array

let foundPfp = await pfps.find((pfp: any) => pfp === data.pfpId);
foundPfp.shift();
console.log('first element removed', foundPfp);

or if you want to remove a specific element from an array:

const pfps = ["63c959f37337160e2de8b7e4/20230122173537/profilepicture.png","63c959f37337160e2de8b7e4/20230122173616/profilepicture.png"]
const indexOfElementToRemove = pfps.indexOf("63c959f37337160e2de8b7e4/20230122173537/profilepicture.png");
pfps.splice(indexOfElementToRemove, 1);
console.log(pfps);

CodePudding user response:

I would use the filter() method. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

let pfps = ["63c959f37337160e2de8b7e4/20230122173537/profilepicture.png","63c959f37337160e2de8b7e4/20230122173616/profilepicture.png"]
pfps = pfps.filter(item => item!="63c959f37337160e2de8b7e4/20230122173616/profilepicture.png");
  • Related