When it comes to iterating through arrays in nodejs

Can someone assist me with using a for loop on an array to search for titles? I have a basic ADD TODO form input that submits and adds todos or titles to the array:

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

I am pushing user input/todos into the array with this code. Then, I am using EJS to display the result on the webpage <%= todos.title %>. I thought about implementing a for loop that iterates through the array to add conditional if statements checking if any of the titles in the array match the input. If there is a match, I want to prevent pushing the todos and instead log the message ("Error: TODO already exists").

Answer №1

If you want to search for specific titles in an Array, you can utilize the includes() method.

const animals = [{ title: 'lion'}, { title: 'elephant'}, { title: 'monkey'}];

console.log(animals.includes(a=> a.title === 'elephant'));
// expected result: true

Answer №2

To accomplish this task, you can utilize the some() method. When using some, it will return true if the provided function evaluates to true for any element in the array, otherwise it will return false.

 const addTodoItem = (todoList, newTask) => {
  const isTaskPresent = todoList.some((task) => task.title === newItem);
  if (isTaskPresent) {
    console.log(' Error: Task already exists ');
    return todoList;
  }
  return todoList.concat({ title: newTask, completed: false });
};

todos = addTodoItem(todos, req.body.new_task_input);

Answer №3

Discover which todos with specific titles are included in an array as shown below

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

Use the above function when adding new items to the todo list

addTodo("abc")

Since "abc" is already present, an error will be shown in the console

addTodo("xyz")

This time, "xyz" will be added to the todo list

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is it important to use linting for JavaScript and TypeScript applications?

Despite searching extensively on Stack Overflow, I have yet to find a comprehensive answer regarding the benefits of linting applications in Typescript and Javascript. Any insights or resources would be greatly appreciated. Linting has become second natur ...

Adding a total property at the row level in JavaScript

Here is a JavaScript array that I need help with: [{ Year:2000, Jan:1, Feb: }, {Year:2001, Jan:-1, Feb:0.34 }] I want to calculate the total of Jan and Feb for each entry in the existing array and add it as a new property. For example: [{ Year:2000, Ja ...

Tips for transferring the ID from one element to another using JavaScript

I'm attempting to create a slideshow using icons all within one class. The "active" style class will have an ID and represent the current picture. By clicking either the left or right button, I aim to change the style of the active class. const l ...

Tips for utilizing regex to locate words and spaces within a text?

I'm feeling so frustrated and lost right now. Any help you can offer would be greatly appreciated. I am currently dealing with an issue in Katex and Guppy keyboard. My goal is to create a regex that will identify the word matrix, locate the slash that ...

Troubleshooting: Unable to modify value with function in AngularJS

Why can't I change a value using a function in AngularJS? html: <div ng-controler='TestCtrl' id='TestCtrl'> <h1>Test: {{test.name}}</h1> <div ng-hide='showTest'> <div class=&a ...

Steps for adding a border to kendo grid row hover

One of my tasks involved creating a grid using Kendo, and I wanted to display borders on a grid row when the cursor hovers over it. I attempted the following code snippet: .k-grid > table > tbody > tr:hover, .k-grid-content > table > tbody ...

Emphasize a specific line of text within a <div> with a highlighting effect

I'm looking to achieve a similar effect as demonstrated in this fiddle As per StackOverflow guidelines, I understand that when linking to jsfiddle.net, it's required to provide some code. Below is the main function from the mentioned link, but f ...

In PHP, search for a specific value in an array and return the corresponding key from a text file

In my possession is a substantial txt file (3.5 MB) organized in the following manner: sweep#1 expanse#1 0.375 loftiness#1 highness#2 0.375 lockstep#1 0.25 laziness#2 0.25 treponema#1 0.25 rhizopodan#1 rhizopod#1 0.25 plumy#3 feathery#3 feathered#1 -0.125 ...

Validating forms using Ajax in the Model-View-Controller

I am facing an issue with my Ajax form, where I need to trigger a JavaScript function on failure. The code snippet looks like this: using (Ajax.BeginForm("UpdateStages", new AjaxOptions { HttpMethod = "POST", OnSuccess = "refreshSearchResults(&apo ...

What is the best way to retrieve the scope of ng-repeat from another directive located on the same element as ng-repeat?

Is it possible to access a property from the ng-repeat scope in another directive within the same element as the ng-repeat directive? For instance, I would like to be able to use the child.class property in this scenario: <div ng-class="{{ child.class ...

JavaScript - Need to automatically scroll to a different div when scrolling occurs

Currently, my focus is on creating a single-page website where the main content is displayed in large boxes arranged vertically down the page. If you have any suggestions or thoughts on using JavaScript to navigate to each content box more efficiently, I ...

What could be causing my form not to Submit when attempting submission without utilizing the submit button?

Here is the code for my validation: $(function () { function validateForm() { // Code to validate form inputs } $('#myform').submit(validateForm); }); After this, I want to submit the form when a certain action occurs: < ...

Transferring a string from one array to a different array

Looking to assign a string from one array to another in C programming. gates[gatenum]=&seperation[a+1]; Both a and gatenum are integers. The arrays are declared as follows: char seperation[3000][100]; char *gates[100][10]; Essentially, how can I as ...

Error encountered in React Material UI: Appbar - TypeError occurred when attempting to read properties that are undefined (specifically, reading '100')

Currently, I am working on developing a multi-step form using Material UI components. However, upon importing the necessary components, an error is being displayed in my code snippet: import React from 'react'; import { ThemeProvider } from &a ...

Only allow scrolling if the number of child elements exceeds a certain limit

I am looking to implement a scroll feature on the <ul> element when the number of <li>s exceeds a certain threshold. For example, if we have 12 children, I want to display only 7 of them and then scroll through the rest. This is my current app ...

Embracing PWAs with subdomains – seamless installation

One of my Progressive Web Applications (PWA) called app A contains a link to another app, app B. Initially, I hosted both apps on the same subdomain (for example: ) and everything worked perfectly - installing app A also installed app B. However, when I a ...

Is there a way to categorize items by their name in JavaScript?

Currently working with Node, I am in the process of developing an ID3 tag parser to extract the title, album, and artist information from MP3 files. My next step involves organizing the retrieved data by grouping them according to the album name. In my p ...

Tips for dynamically changing the class of a form field in jQuery when it is empty

I am currently working on a form that looks like this; <form id="myform" name="myform"> <input type="text" class="required" value="" name="qwer" /><br /> <input type="text" value="" name="asdf" /><br /> <input type=" ...

What is the best way to "re-upload" drop-down selection using javascript?

I am attempting to automate a drop-down selection process on a website using a headless browser called Firefox Marionette. The website is not under my control, and the process involves: A primary drop-down menu where I can choose an option. A secondary dr ...

Unable to delete a row from a dynamically generated table using jQuery

I am currently working on a project that involves creating a table based on results from a servlet. The table includes checkboxes, and when a checkbox is checked, a button at the bottom of the table should appear. This button calls a remove function to del ...