Search code examples
javascriptangular-cliangular2-services

This is a delete method by ID, returning a TodoDataService, now I want to filter a todo item to delete


I'm creating an Angular C.L.I small project, that adds and removes To-do items from a list. In this delete method below, what filter method does in this context?

deleteTodoByID(id: number):TodoDataService {
    this.todos = this.todos.filter(todo => todo.id !==id);
    return this;
}

Solution

  • Array.filter creates a new array of all the elements that 'pass' the filter (and return a truthy value). So in this example, the filter will produce a new array with any elements where the ID of the element isn't equal to the ID given to the function. this.todos is then set equal to this new array.

    This has the effect of removing any objects within the array where the id is equal to the id given to the function deleteTodoByID.