2

Here is my code: I want to iterate through each pair of elements of the arrays, and if the strings in each pair contain one or more common substrings, console.log(true), otherwise console.log(false). So, output should be true, false, because "first" and "criss" have common substrings ("r", "i", "s") Here is my code for now;

const a = ["first", "hi"];
const b = ["criss", "student"];

function commonSubstring(a, b) {
  a.forEach(a1 =>
    b.forEach(a2 => {
      for (i = 0; i < a1.length; i++) {
        if (a1.charAt(i) == a2.charAt(i)) {
          console.log(true");
        }
      }
    })
  );
}
commonSubstring(a, b);

Thanks for answers in advance!

2
  • Can you give an example of common substrings like first and student has st common in them. Is that what you mean or Is it the full string, or do you mean characters Commented Jun 11, 2019 at 9:28
  • You are only comparing the same character position in both test strings with if (a1.charAt(i) == a2.charAt(i)), so the only thing “first” and “criss” have in common would be the “s” at position 4 (3, if you start counting at 0.) Commented Jun 11, 2019 at 9:34

2 Answers 2

1

You could take a Set and check if a character is common.

function common(a, b) {
    return [...a].some(Set.prototype.has, new Set(b));
}

var a = ["first", "hi"],
    b = ["criss", "student"],
    result = a.map((v, i) => common(v, b[i]));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

const a = ["first", "hi"];
const b = ["criss", "student"];

function commonSubstring(a, b) {
  let result = [];
  a.forEach(a1 => {
    let found = false;
    b.forEach(a2 => {
      for (i = 0; i < a1.length; i++) {
        if (a1.charAt(i) == a2.charAt(i)) {
          //console.log(true);
          found = true;          
        }
      }
    })
    result.push(found);
    //console.log(found)
  });
 return result.join(',');
  
}
console.log(commonSubstring(a, b));

3 Comments

How to use return instead of console.log?
return not array of result but inline "true" and then "false"
You can join the array with ,. See the updated answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.