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

109
Vistas
solo obtenga el último resultado en un for loop js

así que quería que mi bucle for se ejecutara a través de un texto y contara cuántas veces se mencionaron las palabras: 'realmente', 'básicamente' y 'muy'.

aquí está el texto:

let story = 'El fin de semana pasado, tomé el paseo en bicicleta más hermoso de mi vida. La ruta se llama "The 9W to Nyack" y en realidad se extiende desde Riverside Park en Manhattan hasta South Nyack, Nueva Jersey. ¡Es realmente una aventura de principio a fin! Es un circuito de 48 millas y básicamente me tomó un día entero. Me detuve en Riverbank State Park para tomar algunas fotos muy artísticas. Sin embargo, fue una parada muy corta, porque me quedaba un largo camino por recorrer.' ;

let storyWords= story.split(' ');

esta es la funcion:

 function count() { let reallycount = 0; let verycount =0; let basicallycount = 0; for (let i = 0; i < storyWords.length; i++) { if (storyWords[i] === 'really'){ reallycount += 1; console.log ('really count :' + reallycount); } else if ( storyWords[i] === 'very'){ verycount += 1; console.log ('very count :' + verycount); } else if ( storyWords[i] === 'basically'){ basicallycount += 1; console.log ('basically count :' + basicallycount); } } } count();

Los resultados:

mucho contar :1, realmente contar :1, básicamente contar :1, mucho contar :2, realmente contar :2, realmente contar :3,

Mi pregunta : así que solo quiero mostrar el último resultado de muy, básicamente y realmente contar. en otras palabras, quiero que los resultados sean:

básicamente cuenta :1, muy cuenta :2, realmente cuenta :3,

¿Cómo puedo ocultar/eliminar los otros resultados?

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Aquí hay una forma un poco más universal de su función counts() que funciona de manera más funcional:

 const story = `Last weekend, I took a very beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It's really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some very artsy photos. It was a really short stop, though, because I had a really long way left to go.` ; function counts(str, words){ const arr=str.toLowerCase().split(/\s+/); return arr.reduce((a,w)=>{ if(words.indexOf(w)>-1) a[w]=(a[w]||0)+1 return a }, {} ) } console.log(counts(story,["really","actually","very"]));

about 4 years ago · Santiago Trujillo Denunciar

0

Puede extraerlo a variables y luego registrarlo en la consola

 function count() { let reallycount = 0; let verycount = 0; let basicallycount = 0; for (let i = 0; i < storyWords.length; i++) { if (storyWords[i] === "really") { reallycount += 1; } else if (storyWords[i] === "very") { verycount += 1; } else if (storyWords[i] === "basically") { basicallycount += 1; } } console.log("basically count :" + basicallycount); console.log("very count :" + verycount); console.log("really count :" + reallycount); } count();
about 4 years ago · Santiago Trujillo Denunciar

0

Otra opción para contar el número de veces que aparece una palabra es usar la función de filter

 const story = "Last weekend, I took a very beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It's really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some very artsy photos. It was a really short stop, though, because I had a really long way left to go." const storyWords = story.split(" ") function count() { const basicallycount = storyWords.filter(word => word === "basically").length const verycount = storyWords.filter(word => word === "very").length const reallycount = storyWords.filter(word => word === "really").length console.log(`basically count: ${basicallycount}` console.log(`very count: ${verycount}` console.log(`really count: ${reallycount}` } count();
about 4 years ago · Santiago Trujillo 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