Vivek Joshi
Vivek Joshi

Reputation: 71

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

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]);

Upvotes: 0

Views: 27

Answers (1)

epascarello
epascarello

Reputation: 207527

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

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

Upvotes: 1

Related Questions