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.