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

208
Views
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 answers
Answer question

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 Report

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 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!