简体   繁体   中英

How to check for email duplication from array in JavaScript?

Have two emails and trying to check if it matches anything in my data array which is an array of emails.

Thought the below would return true or false but it seems to be not working:

 const email1 = test.emailAddress.value;
 const email2 = test2.emailAddress.value;

 data.every(({ email }) => email.value === email1 || email.value === email2);

You can filter your data with the matched array of two emails like so:

 const data = [ {email: 'test@test.com'}, {email: 'test1@test.com'}, {email: 'test2@test.com'} ] const email1 = 'test1@test.com' const email2 = 'test2@test.com' const matched = data.filter(({ email }) => [email1, email2].includes(email)); console.log(matched) 

According to your code, the .every method checks if every email in the data array is either email1 or email2 , if at least one of the emails in the data array fails the condition, the .every method returns false. Which means that the .every method is not suitable for what you want to achieve.

var exists = data.some(({email}) => [email1, email2].includes(email))

Thats with the assumption that data is a array of objects that contain email attribute. If data is simply an array of email strings, then it should be

var exists = data.some(email => [email1, email2].includes(email))

Unless you provide your data it is hard to figure out what is going on. But you can use includes to check if an element is present in an array or not.

The includes() method determines whether an array includes a certain element, returning true or false as appropriate.

if( data.includes(email1) || data.includes(email2)){ // ||  && depending upon your needs
   //do something
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM