Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

85
Visualizações
Creating a function to search an array of strings for a certain word, and returning the element containing that word

The project I am currently trying to complete gives you an array (coffees). The goal is to output whether the coffee needs sugar, cream, or none, based on that if it is a light, medium, or dark roast. For example, light colombian roast should output I'll have the light colombian roast and drink it black. The current code I have does this correctly, except only for the first instance of light, medium, dark being found in the array coffees. Not too sure how to write my function to include all instances of the keyword being found, instead of stopping and storing only the index of the first string the word is in.

const coffees = [
    "light colombian roast", "hawaiian dark roast", "guatemalan blend medium roast",
    "dark madagascar blend", "jamaican dark blue", "jamaican medium roast",
    "salvador robusto light"
]

let output = ""

function searchStringInArray (str, strArray) {
    for (var j=0; j<strArray.length; j++) {
        if(strArray[j].match(str)) {
        return j;
        }

    }
    return -1;
}

for (const coffee of coffees) {
    if (coffee.includes("light")) {  
        let i;
        i = searchStringInArray('light', coffees);
        output += `I'll have the ${coffees[i]} and drink it black`
    }
    else if (coffee.includes("medium")) {
        let k;
        k = searchStringInArray('medium', coffees);
        output += `I'll have the ${coffees[k]} and add cream only`
    }
    else if (coffee.includes("dark")) {
        let n;
        n = searchStringInArray('dark', coffees);
        output += `I'll have the ${coffees[n]} and add cream and sugar`
    }
    output += "\n"
}

console.log(output)
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Instead of making the logic too complex you can simply achieve it via using Array.map() along with switch statement for better performance as compare to multiple if/else clause.

Working Demo :

const coffees = [
  "light colombian roast", "hawaiian dark roast", "guatemalan blend medium roast",
  "dark madagascar blend", "jamaican dark blue", "jamaican medium roast",
  "salvador robusto light"
];

const output = coffees.map(coffee => {
    switch(true) {
      case (/light/i.test(coffee)):
        str = `I'll have the ${coffee} and drink it black`
        break;
      case (/medium/i.test(coffee)):
        str = `I'll have the ${coffee} and add cream only`
        break;
      case (/dark/i.test(coffee)):
        str = `I'll have the ${coffee} and add cream and sugar`
        break;
    }
  return str;
});


console.log(output);

about 4 years ago · Juan Pablo Isaza Relatório

0

I think you're making it too complicated unless I'm missing a step in what you're trying to do. You already loop through each coffee, no need to look it back up again.

for (const coffee of coffees) {
    if (coffee.includes("light")) {  
        output += `I'll have the ${coffee} and drink it black`
    }
    else if (coffee.includes("medium")) {
        output += `I'll have the ${coffee} and add cream only`
    }
    else if (coffee.includes("dark")) {

        output += `I'll have the ${coffee} and add cream and sugar`
    }
    output += "\n"
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda