Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

209
Visualizações
Make function CRUD DeletebyID(id) Javascript by its number of id not by index

Heloo, i am new in learning of javascript. Can you guys help me.. Here's the detail:

I have arrays:

let todos = [
    {id: 1, todo: "learning javascript"},
    {id: 2, todo: "sleeping"},
    {id: 3, todo: "playing"},
];

All i have to do, I want to remove an array object that have number of id:2 by its id (exactly id/number) which is by "number" of value of the object. NOT by index. I want to make CRUD function. But the function only have one parameter, which is ID :

DeleteByID(id) ---> by its number id, not by index.

So, the result will become like this:

   let todos = [
        {id: 1, todo: "learning javascript"},
        {id: 3, todo: "playing"},
    ];

I've already tried my code below..

  function deleteByID(id) {
  for(var i in todos){
    if(todos[i].id == id){
      todos[i].splice(i, id);
      break;
    }
  }
}


    console.log("Delete:", deleteByID(2));

I've tried my code, but it doesn't work. I've tried to googling, but I still dont have any clue for the solution. Please help me guys. Thanks

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You want to splice todos, not todos[i] and you want to remove 1 element, not "id" elements

and you want to return the spliced element

Here you go

let todos = [{
    id: 1,
    todo: "learning javascript"
  },
  {
    id: 2,
    todo: "sleeping"
  },
  {
    id: 3,
    todo: "playing"
  },
];

function deleteByID(id) {
  for (var i in todos) {
    if (todos[i].id == id) {
      return todos.splice(i, 1);
    }
  }
}

console.log("Delete:", deleteByID(2));
console.log("Todos:", todos);

about 4 years ago · Juan Pablo Isaza Relatório

0

Maybe something like this

let todos = [
    {id: 1, todo: "learning javascript"},
    {id: 2, todo: "sleeping"},
    {id: 3, todo: "playing"},
];

function deleteById(datas, id){
    let index = datas.findIndex(data => data.id === id)
  datas.splice(index, 1)
}

console.log(todos)
deleteById(todos, 2)
console.log(todos)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda