Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda