Can forEach be used to remove duplicate names entered by a user in an array, specifically for event calendars?

Struggling to prevent previously added variables from being inserted into an array? I am trying to utilize the findIndex method to search for an element in the array. If the element is not found within the array, I want it to return -1 and then add it; otherwise, an error should be thrown. What could be causing this issue?

The current code allows a new element to be appended to the array without triggering an error.

createNewEvent(){
        let title = prompt('Name your Event: ');
        let date = prompt('When is your event taking place? Use MM/DD/YYYY format: ');

        
    if(this.events.indexOf(title) < 0){

        this.events.push(new Event(title, date));
        } else {
            throw new Error('Please re-name your event');
        }
     
    }


I attempted using indexOf with (title) in the condition to trigger an error based on user input. Additionally, I tried using a for loop to spot [i] in the events array and used forEach to cycle through and identify a matching string.

Answer №1

It appears that you are working with an array of objects. The .indexOf extension method is designed for use with primitive values such as strings. When dealing with objects, a more suitable option would be to utilize the .some extension method. Below is an example of how this can be implemented:

if(!this.events.some(e => e.title === title)){
[...]
}

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

JXBrowser comparable

In a Java project of mine, I have been utilizing JXBrowser to showcase Google Maps for route tracing purposes. However, the license for JXBrowser has recently expired after just one month. Unfortunately, simply requesting another license is not an option ...

How can I communicate a message between a content script and a background page in a Chrome extension?

I'm uncertain if my current approach is the most effective for achieving my goal, so any feedback is welcome. My project involves creating a chrome extension that needs to analyze each word on a webpage against a list of 12,000 elements stored in an ...

Use promises instead of directly calling res.json(data) when working with Node.js

When I make a post request to the payment_url, it triggers the second block of my function. Unfortunately, I am unable to retrieve any data in the then method because I am unsure how to pass the data back to the resolve function. Client-side call paypal. ...

How can you restrict a textbox input to accept only numerical values and decimals using ng-pattern?

I'm working on a code that needs to accept both decimals and integers. How can I verify this using the ng-pattern? An example of the code: Some test cases include: 1) 22 = Should pass, 2) 22.5 = Should pass, 3) 2a = Should fail, 4) @#@ = Should ...

What is the best way to arrange the elements of an array based on the number of divisors

Encountered a challenge while working on some programming exercises. The task at hand is to write a program that sorts an array in descending order based on the number of divisors of each element. In cases where two elements have the same number of divisor ...

The collada loader in three.js assigns the UV texture's color to every model in the scene

Apologies for my poor English skills. I am encountering an issue with the Collada loader in Three.js. In Blender, I have a cylinder with a UV texture applied to it, and when I render it everything looks fine. However, upon exporting and loading it into Thr ...

Link the ServerResponse object to a function

I'm new to ES and facing an issue with binding ServerResponse object to a function. My server follows OAuth protocol: let saveToken = (response) => { console.log('\n') console.log(this.constructor) // Issue [Function: Object ...

Avoiding overlapping in setTimeOut when using jQuery.hover()

Looking to trigger an effect one second after the page loads, and then every 3 seconds in a loop. When the user hovers over a specific element with the ID #hover, the effect should pause momentarily. It should then resume 2 seconds after the user stops hov ...

Separate .env configurations tailored for development and production environments

Managing different content in my .env files is crucial as I work with both next.js and node.js. The settings vary between development and deployment environments. During development: DOMAIN_URL=https://localhost:3000 GOOGLE_CLIENT_ID='abc' For ...

Sidenav Content with all elements having opacity applied

How can I ensure that all page elements have a black background color when the mobile navigation is opened on the left screen, while ensuring that my sidebar and content image do not get overlaid by the black background? Here is my code: function openNav( ...

Invoke the do_action function with JavaScript/jQuery

After successfully logging in through Facebook, my AJAX function sends information to the userpro_ajax_url. In order to run a do_action function within the success block, I am trying the following: <?php ob_start(); do_action('userpro_social_l ...

Extracting individual rows of data from a text file and storing them in separate arrays

Survey data is currently stored in a text file and needs to be organized into separate arrays. An example of the data format is: C 1 1000 1000 C 2 1010.72 1005.04 ...

Why is Jquery Validation failing to function correctly?

I'm having trouble with validating my form using jQuery. I can't seem to figure out why the validation isn't working as expected. You can view my code on this Fiddle. HTML Code: <input id="txtName" placeholder="Enter Name" /> <inp ...

Looking for assistance on how to conceal the ego_bar on Facebook

// ==UserScript== // @name Disable friend suggestions on Facebook // @namespace facebook // @description Remove friend suggestions on Facebook // @include *.facebook.com // @require http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min. ...

disabled button feature not being activated

Although I have browsed through several similar questions, none of them seem to have the solution I require. Here's an angular component code snippet: @Component({ providers: [ FlowsheetService, SubscriptionService ], moduleId: module.id, sele ...

Sending this over to the window's onscroll function

Is there a way to correctly pass the current element to a function designated for the window.onscroll event? My goal is to activate myFunction() when a specific condition occurs. This condition needs to be checked during onscroll init() { window.on ...

Combining two JSON objects into a single JSON object using Jquery/JavaScript

I need to combine two JSON objects into one, here are my current JSON objects: var obj_1 = { "?xml": {"version": "1.0", "encoding": "utf-8"}, "Template": { "Name": "Capital Goods-Tool and Die Maker L5 Set1", "Section": [{ "Id": "Section_ ...

Maintaining the "Date" value in React Native DatePickerIOS when returning from other pages

In my scenario, I am using the DatePickerIOS component. The example in the documentation initializes a new Date() and uses state to store and update the Date value. However, when navigating to another page and returning, the time changes and I find myself ...

Tips for removing the element that meets the criteria from a JSON object list

Apologies for the lack of knowledge in French and for asking what may seem like a silly question, but I need assistance with removing certain elements from a JSON file despite being unfamiliar with JSON and JS. The structure is as follows: ` { "quest ...

Utilize Angular service to deliver on a promise

Currently, I have a service that is responsible for updating a value on the database. My goal is to update the view scope based on the result of this operation (whether it was successful or not). However, due to the asynchronous nature of the HTTP request ...