Search code examples
javascriptarraysinputsplice

How to delete an input stored in array in JS


let input;
const todos = [];

while (input !== 'exit') {
    input = prompt('Type what you want to do');
    if (input === 'new') {
        input = prompt("What's your todo?");
        todos.push(input);
    } else if (input === 'list') {
        console.log(`This is your list of todos: ${todos}`);
    } else if (input === 'delete') {
        input = prompt('Which todo would you like to delete?');
        if (todos.indexOf(input) !== -1) {
            todos.splice(1, 1, input);
            console.log(`You've deleted ${input}`);
        }
    } else {
        break;
    }
}

That's what I've tried so far. I'm starting into programing and this is part of a small exercise that I have to ask from a prompt to add a new todo, list it all and then delete. What i'm trying to do is: take that input stored at input variable and then check if its inside the array, if its positive I want to delete it and not from the index but from the word.

Like:

-delete -eat //check if its inside array //if true delete it from

I apologize if its a dumb question. I tried online and couldn't find it.

Thanks!


Solution

  • Your code fixed below:

    input = prompt('Which todo would you like to delete?');
    const index = todos.indexOf(input);
    if (~index) {
      todos.splice(index, 1);
      console.log(`You've deleted ${input}`);
    }
    

    You can read more about Array.prototype.splice() and the bitwise operator on the corresponding MDN docs.