Home > Blockchain >  How to check if an email address is written more than once or not
How to check if an email address is written more than once or not

Time:07-27

I am using a map in javascript and using the logic if the number of fields is more than the map size then any of the mail addresses are repeated. The problem arises as the map takes empty and undefined values, thus giving the wrong output. Suppose I keep 1st and 2nd fields empty then undefined is the map, showing the error message of multiple emails.

useEffect(() => {
        let count = 0;
        const uniqueEmails = new Set(emailsAndRoles.map((emailsAndRole) => emailsAndRole.email));
       
        console.log('uniqueEmails', uniqueEmails);

        let alreadyExist = false;
        for (let i = 0; i < emailsAndRoles.length; i  ) {
            const email = emailsAndRoles[i].email;
            if (allUsersEmail.includes(email)) {
                alreadyExist = true;
                break;
            }
        }


        if (uniqueEmails.size < emailsAndRoles.length || alreadyExist) {
            setDuplicateEmailMessage('You have entered duplicate email');
            console.log(uniqueEmails.size, emailsAndRoles.length);
        } else {
            setDuplicateEmailMessage('');
            console.log(uniqueEmails.size, emailsAndRoles.length);
        }

        // eslint-disable-next-line
    }, [emailsAndRoles]);

CodePudding user response:

So remove the empty entries. You can do that with filter

emailsAndRoles.map(({ email }) => email).filter(Boolean)
  • Related