Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

134
Views
API issue | URL with parameter

I have an issue with my Delete function, it is deleting always the last data and not the desired data.

Here's my API - DELETE function:

Function to delete the data

app.delete("/api/theTasks/:id", (req, res) => {
    let taskToRemove = Items.find(p => p.id == parseInt(req.params.id));
    let index = Items.indexOf(taskToRemove);
    Items.splice(index, 1);
    res.json(taskToRemove);
});
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Problem:

  1. find also return undefined If it does not find the item.
  2. when you search for the undefined index it'll return -1
  3. if you pass -1 to splice It'll always remove the last element.

Use array filter,

app.delete("/api/theTasks/:id", (req, res) => {
  const result = Items.filter((p) => p.id === parseInt(req.params.id));

  if (result.length === 0) res.status(404).json({ error: "Item not found" });
  res.json(result);
});
about 4 years ago · Juan Pablo Isaza Report

0

My guess is that the task is not found and index ends up being -1, so you end up calling:

Items.splice(-1, 1);

which removes the last element of Items.

You can fix the issue by checking if the item was found and only deleting it if that is true.

app.delete("/api/theTasks/:id", (req, res) => {
    let taskToRemove = Items.find(p => p.id == parseInt(req.params.id));
    if (taskToRemove) {
        let index = Items.indexOf(taskToRemove);
        Items.splice(index, 1);
        res.json(taskToRemove);
    } else {
        res.status(404).json({ error: 'Item not found' });
    }

});
about 4 years ago · Juan Pablo Isaza Report

0

get index is -1; you should check it before splice; or use filter

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!