0

While building a Todo app, I want to filter out an object out of my array with a remove function. So far I got this.

deleteTask(task) {

    let taskList = this.state.tasks;

    var newTask = taskList.filter(function(_task) { return _task != task})

    this.setState({ 
        tasks: newTask
    });

}

Only problem is, the function returns the whole array while using the function. So the Task argument that should return just an object out of my array returns the whole array instead while in my newTask var.

How can I bind or make this function work?

The array which I am wanting to remove an object from is not located in the same Component, dont know if that matters. But for extra info.

3
  • Please add what you are getting inside both task and use arrow functions please => Commented Jan 12, 2019 at 11:44
  • what is the structure of the state.tasks and task parameter? Commented Jan 12, 2019 at 11:47
  • 1
    You'll have to use some unique identifier of the task. Like this: var newTask = taskList.filter(t => t.id != task.id). You might also want to read this: Equality comparisons and sameness Commented Jan 12, 2019 at 11:49

2 Answers 2

2

First off, let's see why _task != task doesn't work as you need. Try this:

const a = { x: 10, y: 'hello' };
const b = { x: 10, y: 'hello' };
console.log(
  a==b,
  a===b,
  Object.is(a,b)
);

Suprising, eh? Read this for more details.

Anyway, you should refactor your code to include an id property in your tasks, so that you can compare two tasks with their ids - no need to worry about weird implementations of object comparisons in JavaScript!

This should then work:

deleteTask(taskId) {
  this.setState(prevState => ({
    tasks: prevState.tasks.filter(task => task.id !== taskId)
  }));
}
Sign up to request clarification or add additional context in comments.

Comments

0

Equality operator in javascript compares the references of the object. So even if both object have same value, since they point to different instances, == will always return false. So as I see you have two options:

  1. Refactor your code to include a id part and which that to compare two tasks.
  2. Use some library like lodash or underscore for deep comparison

1 Comment

Also thanks for the tip. I'll start using the libraries once I understand JS a bit more

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.