skip to Main Content

I’ve got an array of strings and a string. Using a for loop, iterating through both the array and the string, I’m hoping to return the letters that are the same in both.

My solution works until there is a duplicate letter in the array. When there is a duplicate, the
relevant letter gets doubled, for example ‘aaa’ would return ‘aaaaaa’.

Below is the code that I have tried most recently.

const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];

let myString = "apple";

const fruit = fruits[2].toLowerCase();

for (let i = 0; i < fruit.length; i++) {
  for (let j = 0; j < myString.length; j++) {
    if (myString[j].indexOf(fruit[i]) !== -1) {
      console.log(myString[j]);
      return myString(j)
    }
  }
}

2

Answers


  1. You can just check if the whole string matches the fruit,
    then print the letters from that. I got lost in your inner for loops.
    Check this one out:
    https://jsfiddle.net/peu54ry2/

    const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
    const myString = "apple";
    
    for (let i = 0; i < fruits.length; i++) {
      if (fruits[i].toLowerCase() == myString) {
        console.log(fruits[i]);
      }
    }
    Login or Signup to reply.
  2. Assuming you want to look at each word in the array

    You may want to fiddle with the toLowerCases depending on your needs

    const fruits = ["Banana", "Orange", "Apple", "Mango", "Apple"];
    let myString = "apple";
    
    const findCommonLetters = (array, string) => {
      const uniqueStringLetters = new Set(string.toLowerCase()); // unique letters in string
    
      const matches = array.map(fruit => [...new Set(fruit.toLowerCase())]
        .filter(letter => uniqueStringLetters.has(letter)) // find matching letters
        .join(''));
      return matches;
    };
    
    console.log(findCommonLetters(fruits, myString));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search