0

I need help! I want to use a for loop over an array so that it can look for titles, I have a simple ADD TODO form input and I have made it submit and push the todos or titles of the todos,

  todos.push({ title: req.body.add_todo_input, complete: false });

I use this line to push the the users input / the todos to the array, I then use EJS to show the result on the webpage <%= todos.title %>, I decided why not make a for loop that loops over the array so that I can add some conditional if statements that check to see if any of the titles inside the array are equal to the same input, and if so don't push the todos and console log this message (" Error: TODO already exists ").

3 Answers 3

1

You can use the includes() method of Array to look for titles

const pets = [{ title: 'cat'}, { title: 'dog'}, { title: 'bat'}];

console.log(pets.includes(t=> t.title === 'dog'));
// expected output: true
Sign up to request clarification or add additional context in comments.

Comments

0

You can use some() method to achieve this. some returns true, when it finds an element for which the given function returns true, otherwise it will return false.

 const addTodo = (todos, newItem) => {
  const isTodoPresent = todos.some((todo) => todo.title === newItem);
  if (isTodoPresent) {
    console.log(' Error: TODO already exists ');
    return todos;
  }
  return todos.concat({ title: newItem, completed: false });
};

todos = addTodo(todos, req.body.add_todo_input);

1 Comment

Hi, this is exactly what I needed for this concept. Thanks so much! I will learn this logic as much as I can to make sure I have enough knowledge to write like this in the future without needing help.
0

Find out the todo with a title are present in an array like below

let todo = [{title: "abc"}, {title: "def"}]
function addTodo(title) {
  let x = todo.find(item => item.title == title)
  if (x) {
    console.log("todo already present")
  } else {
    todo.push({title: title})
  }
}

When you add new item into todo list then use above function

addTodo("abc")

now "abc" is already exist so it shows error in console

addTodo("xyz")

now this time "xyz" will added into todo list

Comments

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.