Skip to content
Advertisement

function in javascript check repeated word not working [closed]

function numTimesWordRepeated() {
  const str =
    "The weather is good but if the weather is bad we realy need to brace for bad weather";
  const char = {};
  const arr = str.split(" ");

  for (let word of arr) {
    if (!char[word]) {
      char[word] = 1;
    } else {
      char[word]++;
    }
  }
}

console.log(numTimesWordRepeated());

Advertisement

Answer

Please provide more information about your problem. Anyway you have to return something from the function otherwise it will not console log your char map. If you don’t return anything in the function it returns undefined.

function numTimesWordRepeated() {
    const str =
        "The weather is good but if the weather is bad we realy need to brace for bad weather";
    const char = {};
    const arr = str.split(" ");

    for (let word of arr) {
        if (!char[word]) {
            char[word] = 1;
        } else {
            char[word]++;
        }
    }

    return char
}
console.log(numTimesWordRepeated());

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement