Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

166
Vistas
How to compare two arrays of strings, find all matches, when there might be a sentence?

This is a fun one - I am building a profanity checker!

For the purposes of this exercise, let's have an array of forbidden words, like so:

const forbiddenWords = ['apples', 'oranges', 'blue carrots', 'mushy green peas'];

Then I will have an input field for a user to input the something. It could be an infinite combo of words, but I would like to find ALL instances of the forbidden words and return them as an array. I've thought of this function, which gets me really close:

const forbiddenWords = ['apples', 'oranges', 'blue carrots', 'mushy green peas'];
const userInput = 'Broccoli is my favorite food. I hate oranges and blue carrots';

    const checkIfValidInput = () => {
        // Will return an array that looks like: ['Broccoli', 'is', 'my', 'favorite', ...]
        const splitWords = userInput.split(" ");
        const array = [];
        for (let i in forbiddenWords) {
            if (splitWords.indexOf(forbiddenWords[i]) !== -1) {
                array.push(forbiddenWords[i]);
            }
        }
        return array.sort((x, y) => x - y);
    };

Running the above will make the result of array be ['oranges', 'blue', 'carrots']. How could I build out the function to check for 'blue carrots' or 'mushy green peas' all in one? I'd like the above function to return: ['oranges', 'blue carrots']. Thoughts?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You can use regex for this situation. This will also give you ability to match with case insensitivity

const checkIfValidInput = () => {
  const forbiddenWords = ['apples', 'oranges', 'blue carrots', 'mushy green peas'];
  const userInput = 'Broccoli is my favorite food. I hate oranges and blue carrots';
  
  const result = forbiddenWords.reduce((acc, words) => {
    const match = userInput.match(new RegExp(words, ['gi']))
    return match ? acc.concat(match) : acc
  }, [])
  result.sort()
  console.log(result)
}

checkIfValidInput()

Also, array.sort((x, y) => x - y); is not required as the values you have are string. You can rely on array.sort() or if you really want to do manual sort, try string.localeCompare(string2)

about 4 years ago · Juan Pablo Isaza Denunciar

0

You're probably best off creating a regular expression. This way, you can skip the next to split and ignore capitalization issues

You can do this like

var regexStr = "";
for (let i = 0; i < forbiddenWords.length; i++) {
  if (i != 0) regexStr += "|";
  regexStr+= "(" + forbiddenWords[i] + ")";
}

var regex = RegExp.compile(regexStr,"gim");

var matches = userInput.match(regex);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can check the sentence with every single phrases whether it's a match or not and if it's then you can return the phrase and store in a variable.

Technically, using of filter() and includes() would resolve the task. Lemme know if it helps.

let matched = forbiddenWords.filter(phrase => { 
    if(userInput.includes(phrase)) return phrase;
});

return matched;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda