else if(input === 'remove'){
let search = prompt('what index do you want to remove');
for(let j=0;j<todos.length;j++){
console.log(`current data is:${todos[j]}`);
if(todos[j] === search){
console.log(`data to be delete is present`)
todos.splice(todos[j],1);
console.log(`data deleted is ${todos[j]}`)
}
}
if todos contains [task1, abc, def]
my output is :
current data is:task1
current data is:abc
current data is:def
data to be delete is present
data deleted is undefined
How do I remove the element that is todos[j] from the list todos[]
search = "def";
let todo = ["task1", "abc", "eyg7eg", "ugfuegf7uegf", "def"];
todo.forEach(function (elem, i = 0) {
if (elem === search) todo.splice(i, 1);
i++;
});
used for each for iteration the whole array to find the desired element, then if element === search is true then use splice to delete that element
Your code had 2 problems:
Fixing theses 2 things, your code works fine, just like this:
let todos = ['task1', 'abc', 'def'];
let search = prompt('what index do you want to remove');
for(let j=0;j<todos.length;j++){
let currentData = todos[j];
console.log(`current data is:${currentData}`);
if(todos[j] === search){
console.log(`data to be delete is ${search}`)
currentData = todos.splice(j,1);
console.log(`data deleted was ${currentData}`)
}
}
For instance, CONSOLE EXIT for 'abc' searched:
current data is:task1
current data is:abc
data to be delete is abc
data deleted was abc
HERE I leave you a working copy of your own code with all that fixes.
As an Extra, I give a different version "mixing" several of others mates answers:
const todos = ['task1', 'abc', 'def'];;
const search = 'abc';
todos.some(
(item, index) => { if (item === search) { todos.splice(index, 1); return true;} }
);
console.log(todos);