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

239
Vistas
¿Cómo contar palabras similares en una cadena y mostrar su conteo individual en una nueva cadena?

Estoy tratando de crear una función que tome una cadena como entrada. Esta función debe contar cada palabra y mostrar un número de conteo al lado de la palabra individual. El recuento debe aumentar por iteración de la palabra.

Donde la entrada es una string == "this is this sample" y la salida esperada es "this(2) is(1) this(2) sample(1)"

Esto es lo que tengo hasta ahora:

 function wordCounter(string) { const array = string.split(" "); let count = 0; for (let i = 0; i < array.length; i++) { // if statement? // } }

Por lo que entiendo, la cadena deberá convertirse en una matriz para que se repita. Sin embargo, tengo dificultades para entender cómo cada palabra específica puede tener su propio contador. También investigué .reduce(), pero me está costando implementarlo.

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

0

Mi primera idea en bruto sería hacer algo como esto:

 function wordCounter(string) { const array = string.split(" "); let count = {}; let result = ''; for (let i = 0; i < array.length; i++) { if(count[array[i]]) { count[array[i]]+=1; } else { count[array[i]] = 1; } } Object.keys(count).map(key => { result += key + '('+ count[key]+') '; }); return result; } console.log(wordCounter('hello this is a test'));

about 4 years ago · Juan Pablo Isaza Denunciar

0

Esto parece funcionar, pero tenga en cuenta que está codificado con la intención de no contar espacios en blanco e incluye puntuación/caso al considerar el recuento de palabras.

 function wordCounter(string) { var array = string.split(" "); //"dictionary" is an object. We'll store words in it like properties. var dictionary = {}; var final = ""; var current; var currentCount; for (let index = 0; index < array.length; index++) { current = array[index]; //If the current array item isn't a blank... if (current != "") { //If the word isn't already in dictionary... if (dictionary[current] == null) { //We add it and set it to 1. currentCount = 1; dictionary[current] = currentCount; } //Otherwise... else { //We get the current value, add 1, and set the property to the new value. currentCount = dictionary[current] + 1; dictionary[current] = currentCount; } //Now we append the word, parentheses, and current count. final += current + "(" + currentCount + ") "; } } //Once the loops is done, if our word is greater than 0 characters, we slice the last one (the extra space from our last iteration). if (final.length > 0) { final = final.slice(0, -1); } //Print the final text. alert(final); } window.addEventListener('load', function() { wordCounter("This right here is this the sample of the sample you wanted. It's not the same as your sample, but it's a sample none the less."); wordCounter(""); wordCounter(" "); wordCounter(" this this and this "); });

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