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
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);
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)