Soy nuevo en el lenguaje javascript y todavía estoy aprendiendo algunos de los tipos de datos y obtengo ejercicios que no puedo comprender, por favor ayúdenme.
La pregunta del ejercicio:
'El amor es lo mejor que hay en este mundo. Algunos encontraron su amor y algunos todavía están buscando su amor. Cuente el número de palabras amor en esta oración.
así que probé algunos de los métodos básicos como,
y no puedo contar las palabras amor y el índice de palabras de amor dado.
¿Cómo puedo codificar esto para encontrar las respuestas?
Esto debería funcionar.
let sentence = "Love is the best thing in this world. Some found their love and some are still looking for their love." console.log(sentence.split("love").length)Esto debería funcionar
const sentence = 'Love is the best thing in this world. Some found their love and some are still looking for their love.' const occurrences = sentence.match(/love/gi); // (g is is for match all occurrences, i is for case insensitive) console.log("number of occurrences of 'love'", occurrences.length)Para hacerlo un poco más genérico y mostrar el uso de reduce:
const data = "Love is the best thing in this world. Some found their love and some are still looking for their love" const dataArray = data.split(' '); const wordMap = dataArray.reduce((result, word) => { result[word.toLowerCase() ]= result[word.toLowerCase() ] ? result[word] + 1 : 1; return result }, {}); console.log(wordMap["love"]) console.log(wordMap["is"]) console.log(wordMap["best"])