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.
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'));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 "); });