1

I am trying to find if second array has any string from the first one. Not sure what I am doing wrong

const domainAlertList = ["@domain1", "@tomato2", "@carrot3"];

const search = ["test@domain1.com", "test@tomato2.com"];

const myFunc = () => {
  return search.some((r) => domainAlertList.includes(r));
};

console.log(myFunc());

It returns false instead of true

Sonny49
  • 425
  • 3
  • 18
  • [this could help](https://stackoverflow.com/questions/16312528/check-if-an-array-contains-any-element-of-another-array-in-javascript). It is basically the same question you asked. – Zirix Mar 05 '22 at 10:36
  • You need to change the test; `test@domain1.com` includes `@domain1`, not the other way around. –  Mar 05 '22 at 10:37
  • @ChrisG if you could write the code that would be helpful – Sonny49 Mar 05 '22 at 10:39
  • @Zirix my code is exactly same but it doesn't work – Sonny49 Mar 05 '22 at 10:39
  • Here's one way: https://jsfiddle.net/b9s53ha6/ –  Mar 05 '22 at 10:43
  • You need to understand why your code doesn't work. Array.includes looks for an element that matches. But the domain is just a part of the email. String.includes on the other hand looks for a partial match. However your code does it, it needs to compare every email against every domain. Your code doesn't do that. –  Mar 05 '22 at 10:45

5 Answers5

2

const domainAlertList = ["@domain1", "@tomato2", "@carrot3"];

const search = ["test@domain1.com", "test@tomato2.com"];

const myFunc = () => {
  return domainAlertList.some((r) => {
      return search.some(t => t.includes(r))
  });
};

console.log(myFunc());
palmarbg
  • 159
  • 7
1

There are many ways to approach this. One of them could be the indexOf() method.

let str = "test@domain1.com";

str.indexOf('domain1') !== -1 // true

source

Zirix
  • 11
  • 1
0

You have to map through the second array too like this

const domainAlertList = ["@domain1", "@tomato2", "@carrot3"];

const search = ["test@domain1.com", "test@tomato2.com"];

const myFunc = () => {
  return search.some((r) => domainAlertList.some(domain=>{domain.includes(r)});
};

console.log(myFunc());
Icekid
  • 435
  • 3
  • 14
0

You can iterate and use array filter function.

const domainAlertList = ["@domain1", "@tomato2", "@carrot3"];
const search = ["test@domain1.com", "test@tomato2.com"];

let r = []
domainAlertList.forEach(i => {
  r.push( search.filter(i1 =>  i1.includes(i)) )  
})
newArr = r.map((a) => {
  if(a.length != 0) {
    return a
  }
}).filter((a) => a);
console.log(newArr)
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79
0
const domainAlertList = ["@domain1", "@domain1", "@carrot3"];

const search = ["test@domain1.com", "test@domain1.com"];

const myFunc = () => {
  return domainAlertList.some((domain) =>
    search.some((email) => email.includes(domain))
  );
};

console.log(myFunc());
Sonny49
  • 425
  • 3
  • 18