Home > OS >  Is there a way to exclude elements from an array if a user enters a name that has already been used
Is there a way to exclude elements from an array if a user enters a name that has already been used

Time:02-04

I am having trouble figuring out how to disallow previously added variables into an array. I'm attempting to use findIndex method to find an element within the array and return -1 if the element does not exist within array then push it in, otherwise it should throw an error. What am I doing wrong?

The code just allows the new element to be added to the array and never throws the 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 tried using indexOf and the (title) within the conditional to allow it to throw an error from user input. I also attempted to use a for loop to identify the [i] within the events array and used forEach to iterate through, and catch a string of the same name.

CodePudding user response:

I see you have an array of objects. The .indexOf extension method only works with primitive values ex strings. For objects, I would just use the .some extension method - something like this:

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

CodePudding user response:

what I do in such cases is to add those values as keys on an empty object

let obj = {};
obj[ newvalue ] = "something";

then, when you are done:

let values = Object.keys( obj );

CodePudding user response:

Seems like you want the javascript array.includes() method (not C#)

  • Related